I'm trying to check if there is a record of 'uid' in indexed db from a service worker. If it's not defined, I need to add a value to it.
This is my code, I already tried in some ways that I found around other questions and sites, but none worked.
function checkUid() {
console.log('checking uid...');
var request = indexedDB.open('db',1);
request.onsuccess = function(event) {
var db = event.target.result;
var store = db.createObjectStore('Users', {keyPath:"users"});
var transaction = event.target.transaction;
db.transaction( '' ).objectStore( '' ).get( 'uid' ).onsuccess =
function(uid)
{
if (uid) {
console.log('uid found!');
console.log(uid);
console.log('uid end');
} else {
console.log('not found!');
db.transaction( '' ).objectStore( '' ).set( 'uid', 'aaaaa' );
console.log('uid end');
}
}
}
How can I do this?
This code opens the database with the name example, creates the object store called users if needed, gets the object with the key x123 from that store, and creates the object if it doesn't already exist.
function checkUid() {
let openRequest = indexedDB.open("example")
openRequest.onupgradeneeded = () => {
console.log("update needed")
openRequest.result.createObjectStore("users")
}
openRequest.onsuccess = () => {
console.log("opened database")
let store = openRequest.result.transaction("users", "readwrite").objectStore("users")
let uid = "x123"
let getRequest = store.get(uid)
getRequest.onsuccess = () => {
let result = getRequest.result
if (result) {
console.log("found:", result)
} else {
console.log("not found")
store.add("aaaaa", uid)
}
}
}
}
Use put() instead of set(), it will update the entry, or create one if it doesn't exist.
https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put
Related
Background:
I need to create a stored procedure in JavaScript (within CosmosDB) where: For every Feedback document, replace/update Feedback.id with new id
var NewID = "5678"
{
"Feedbacks" : [
{
"id": "1234"
}
{
"id": "1234"
}
]
}
This is what I am doing:
I have created a function called UpdateID and set the parameters to OldID and NewID. I am saying iterate through the document, and for every OldID value,, replace with the NewID. I am moreso familiar with Python so this is a bit different for me and I am not sure this is the correct approach.
For every iteration in doc.Feedbacks:
function UpdateID(OldID, NewID) {
if (Feedbacks.id = "OldID")
}
Any suggestion will be helpful
There are a handful of ways to write the javascript, but here's one way that should get on the right track:
function UpdateID(oldID, newID) {
//get just the records that need updating
var isAccepted = __.filter(
function(doc) {
return doc.Feedbacks && doc.Feedbacks.findIndex(function(feedback){
return feedback.id == oldID
}) > -1;
},
function (err, feed, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found'
if (!feed || !feed.length) {
var response = getContext().getResponse();
response.setBody('no docs found');
}
else {
//update the documents that have the old id
UpdateDoc(oldID, newID, feed)
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
//function based on https://stackoverflow.com/questions/36009939/documentdb-updating-multiple-documents-fails
function UpdateDoc(oldID, newID, documents) {
console.log("updating " + documents.length + " docs")
if (documents.length > 0) {
var document = documents[0];
// DocumentDB supports optimistic concurrency control via HTTP ETag.
var requestOptions = { etag: document._etag};
document.Feedbacks = document.Feedbacks.map(function(feedback){
if(feedback.id === oldID) {
feedback.id = newID;
}
return feedback;
});
// Update the document.
var isAccepted = __.replaceDocument(document._self, document, requestOptions, function(err, updatedDocument, responseOptions) {
if (err) {
responseBody.error = err;
throw err;
}
});
// If we hit execution bounds - throw an exception.
if (!isAccepted) {
responseBody.log += "Update not accepted";
response.setBody(responseBody);
}
else {
documents.shift();
if(documents.length > 0){
UpdateDoc(oldID, newID, documents);
}
}
}
}
I am writing a cloud function in which i am creating or initializing firebase app in a for loop with new names, my question is that , is it necessary to call app.delete() function on every instance or not?
snapshot.forEach(doc => {
counter++;
// console.log(counter," in first");
// console.log(doc.id, " is the doc ID");
var home = doc.get('home');//e.g: hyperoffice
var switches = doc.get('switches');
var action = doc.get('action');//ON or OFF
var repeat=doc.get('repeat');// true or false
try {
// console.log("home ", home, " switches ", switches);
let defapp = admin.initializeApp({ databaseURL: databaseUrl }, `${home}${counter}`);
var databaseUrl = `https://${home}.firebaseio.com/`;
switches.forEach(s => {
let dbRef = admin.database(defapp).ref(`Controls/${s}`);
dbRef.once("value").then(val => {
var data = val.val();
// console.log("this is data", data);
var payload_on = data.payload_on;
var payload_off = data.payload_off;
let valRef = admin.database(defapp).ref(`Controls/${s}/value`);
if (action === "ON") {
// on the device
return valRef.set(payload_on);
}
else if (action === "OFF") {
//off the device
return valRef.set(payload_off);
} else {
console.log("Undefined action field in firestore");
}
return null;
}).catch(err => {
console.log("Error", err);
});
});
} catch (error) {
console.log("Eroor: ", error);
}
finally {
console.log("in finally block 67");
}
});
Strictly speaking, you don't have to, but you will leak a lot of memory over time, and your function might crash in a future invocation. Your function should always clean up unused memory before it terminates. This means that you should delete any initialized apps, unless you want to use that exact same app instance in a future invocation.
I am trying to write a firebase function which will check the the "user" and behave according to that on database write event. However when i query the database it returns null everytime and i didnt figure out what i am doing wrong. Any help is appreciated.
Thanks in advance.
My realtime database structure is like this:
ilk-projemiz-cd55baddclose
users
edRIPg8BcZU9YPbubp7HtQo7phl1
sayilar: 1532
status: "on"
hakan
sayilar: 5000
status: "waiting"
mehmet
sayilar: 7000
status: "on"
My firebase function file is this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.sayi = functions.database.ref("/users/{uid}/status").onWrite(event => {
const status = event.data.val();
var user = event.data.ref.parent.key;
if (status =="on") {
console.log(status);
const events = event.data.adminRef.child('users');
const query =events.orderByChild('status').equalTo('on').limitToFirst(2);
query.on("value", sorunsuz,sorunlu);
}
});
function sorunlu(error) {
console.log("Something went wrong.");
console.log(error);
}
function sorunsuz(data) {
console.log("11111");
var fruits = data.val();
console.log(fruits); //it returns null here
var keys = Object.keys(fruits);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if(key==user){
//console.log(fruits[key].sayilar);
console.log("aaa");
}else{
console.log("bbbb");
}
}
}
This line: const events = event.data.adminRef.child('users'); tries to access a users node under the status node. And I think what you wanted to do is access the users node under the root reference.
Use the Admin SDK instead:
const events = admin.database().child('users');
Update: the user variable is out of scope, so I suggest you move the sorunsuz() function to be inside the on() function:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sayi = functions.database.ref("/users/{uid}/status").onWrite(event => {
const status = event.data.val();
var user = event.data.ref.parent.key;
if (status =="on") {
console.log(status);
const events = admin.database().child('users');
const query =events.orderByChild('status').equalTo('on').limitToFirst(2);
query.on("value",
function(data) {
console.log("11111");
var fruits = data.val();
console.log(fruits); //it returns null here
var keys = Object.keys(fruits);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if(key==user){
//console.log(fruits[key].sayilar);
console.log("aaa");
}else{
console.log("bbbb");
}
}
}, sorunlu);
}
});
function sorunlu(error) {
console.log("Something went wrong.");
console.log(error);
}
you have to listen to users node
functions.database.ref("/users/{uid}/status"),
this path is not exist anywhere thats why you are getting null.
exports.sayi = functions.database.ref("/users").onWrite(event => {
const status = event.data.val(); //this data will be new
//Use above value to refer things
if (event.data.previous.exists()) {
//Update operation
}
});
I'm trying to check if an element exist before inserting it in my bdd.
I have to do this in order to (in the future) modify this existing element.
I'm using PouchDb and PouchDb-find with Node 6.9.1.
Actually I'm doing this:
for(var i = 0; i < 10;i++ ){
(function(_count, _pdb){
var count = _count;
var db = _pdb;
db.find({
selector: {numeroCandidat: parseInt(results[count].no_apb)}
}).then((result) => {
if(result.docs.length != 0){
console.log("l'étudiant existe");
}else{
console.log("l'étudiant n'existe pas");
var etudiant = {
"numeroCandidat": results[count].no_apb,
"nom": results[count].nom,
"numeroGroupe": "gr" + results[count].groupe,
"filiere": results[count].libelle,
};
db.post(etudiant).then((response) =>{
// handle response
console.log("STUDENT CREATED");
}).catch(function (err) {
console.log(err);
});
}
}).catch(function (err) {
});
})(i, this.pdb);
};
But the problem is : Due to the asynchronous version of my select query... if an element exists two times it appends that the second select occurred BEFORE the insertion of the first element, and I have this element two times in my database. I don't know how to deal with this one.
SO.. I'v found a workaround !
Simply create a function that I call recursivly after writting into my database.
Goodbye for loop.
var createStudents = function(_count, _pdb, _students){
if(_count >= 10) return;
console.log(_count);
var count = _count;
var db = _pdb;
var students = _students.slice(0);
db.find({
selector: {numeroCandidat: parseInt(students[count].no_apb)}
}).then((result) => {
if(result.docs.length != 0){
console.log("l'étudiant existe");
createStudents(++count,db,results);
}else{
var etudiant = {
"numeroCandidat": students[count].no_apb,
"nom": students[count].nom,
"numeroGroupe": "gr" + students[count].groupe,
"filiere": students[count].libelle,
"etudiantComms": [
{"commentaire": students[count].commentaire}
]
};
db.post(etudiant).then((response) =>{
// handle response
console.log("STUDENT CREATED");
createStudents(++count,db,results);
}).catch(function (err) {
console.log(err);
});
}
}).catch(function (err) {
});
}
createStudents(0,this.pdb,results);
I have a utility function which pass parameters 'name page callback' to the function. Why not work as i tried so many times?
PLUS: seems 'query.tag_id = name' work for me but why query[name] = name did not work so that i can pass whatever name i like;That's, i want to pass the variable /name/ as the property name so that i can use whatever name i like. For example, i can find posts by user_id when i pass user_id variable as the name value. Also i can find posts by its tag_id when i pass tag_id variable as the name value so it's much more flexible than when i use 'query.user_id = name' to do it ,where the name can only be user_id variable or value
NO LIBRARY USED EXCEPT EXPRESS AND NODEJS WITH CONNECT-FLESH, MONGOOSE ETC.
// post_proxy/post.js
"use strict";
let moment = require('moment'),
Post = require('../models/Post'),
User = require('../models/User'),
Comment = require('../models/Comment'),
postProxy = require('../db_proxy/post'),
tagProxy = require('../db_proxy/tag');
module.exports = {
getTen: (name,page,callback)=>{
var query = {};
//name = query;
if(name){
query[name] = name;
console.log('query[name] is'+ Object.keys(query));
}
Post.count(query, ( err, count)=>{
if (err) {
return callback(err);
}else{
console.log( `Number of posts: ${count} . query is ${query}` );
Post.find(query).skip((page-1)*10).limit(10).sort({created_at: -1}).exec((err,posts)=>{
if (err) {
return callback(err);
}
console.log('Posts inthe getTen function is: '+posts);
const modifiedPosts = posts.map(post=>{
return post.processPost(post);
});
console.log('modifiedPosts: '+modifiedPosts);
callback(null, modifiedPosts, count);//provide the params(caluated values),and what to do? you need to figure it out yourself
});
}
});
}
// controller/post.js:
"use strict";
let moment = require('moment'),
Post = require('../models/Post'),
User = require('../models/User'),
Comment = require('../models/Comment'),
postProxy = require('../db_proxy/post'),
tagProxy = require('../db_proxy/tag');
module.exports = {
getTagsPost: (req,res)=>{
const tag_id = req.params.tag_id;
const page = req.query.p ? parseInt(req.query.p) : 1;
//let loginedUser;
console.log('entering into the tagpost');
postProxy.getTen(tag_id, page, (err, posts, count)=> {
if (err) {
console.log('some error with getting the 10 posts:'+ err);
//next(err);
posts = [];
}
// if(req.user){
// loginedUser = req.user.processUser(req.user);
// }
//userProxy.getUserById(user_id, theuser=>{
console.log('tag posts for'+ tag_id +posts);
res.render('post/tagPosts', {
title: 'specific tag page',
user: req.user ? req.user.processUser(req.user) : req.user,
//postUser: req.user ? (req.user._id == user_id ? loginedUser : theuser) : theuser,
posts: posts,
page: page,
isFirstPage: (page - 1) == 0,
isLastPage: ((page - 1) * 10 + posts.length) == count,
messages: {
error: req.flash('error'),
success: req.flash('success'),
info: req.flash('info'),
}, // get the user out of session and pass to template
});
});
},
...
}
//route:
router.get('/tag/:tag_id', post.getTagsPost);
UPDATE:
Did not find an answer so i change it to the following and solve the problems:
getTen: (name,tag_id,user_id,page,callback)=>{
var query = {};
if(name){
if(user_id){
query.user_id = name;
}else{
query.tag_id = name;
}
console.log('query[name] is'+ Object.keys(query));
}
...
}
UPDATE: Did not find an answer so i change it to the following and solve the problems:
getTen: (name,tag_id,user_id,page,callback)=>{
var query = {};
if(name){
if(user_id){
query.user_id = name;
}else{
query.tag_id = name;
}
console.log('query[name] is'+ Object.keys(query));
}
...
}