I'm looking to create Parse.com roles programmatically because from what I've gathered you can not create parent/child relationships or roles referencing roles in the data browser. I currently do not have any roles in Parse. When I run the following code I get 400 (Bad Request) in my JS console.
$scope.activateRoles = function(){
console.log("activating vendor");
Parse.Cloud.run("activateVendor ", {
success: function (IDK) {
alert("The user roles were activated");
},
error: function (error) {
alert("The user roles were not activated.", error);
}
});
}()
Parse.Cloud.define("createRoles", function(request, response){
Parse.Cloud.useMasterKey();
var admin = new Parse.ACL();
admin.setPublicReadAccess(false);
admin.setPublicWriteAccess(false);
admin.getReadAccess("Uh792HOaqi");
admin.getWriteAccess("Uh792HOaqi");
admin.setReadAccess("Uh792HOaqi", true);
admin.setWriteAccess("Uh792HOaqi", true);
var adminRole = new Parse.Role("admin", admin);
adminRole.save();
var agentRole = new Parse.Role("agent", admin);
agentRole.getRoles().add(adminRole);
agentRole.save();
var vendorRole = new Parse.Role("vendor", admin);
vendorRole.getRoles().add(adminRole);
vendorRole.save();
})
Got to make sure to call success/error. You also want to watch out for making sure to add users to a role that's already been saved. You also can only add roles to a role if the role your adding has already been saved.
Here's what will work:
Parse.Cloud.define("createRoles", function(request, response){
Parse.Cloud.useMasterKey();
var admin = new Parse.ACL();
var adminRole = new Parse.Role("admin", admin);
adminRole.save().then(function(adminRoleSaved){
var promises = [];
var agentRole = new Parse.Role("agent", admin);
agentRole.getRoles().add(adminRoleSaved);
promises.push(agentRole.save());
var me = new Parse.Query(Parse.User);
me.get(request.params.id, {
success: function(me) {
adminRoleSaved.getUsers().add(me);
adminRoleSaved.save();
},
error: function(error){
}
});
var vendorRole = new Parse.Role("business", admin);
vendorRole.getRoles().add(adminRoleSaved);
promises.push(vendorRole.save());
Parse.Promise.when(promises).then(function() {
response.success();
}, function(error) {
response.error(error);
});
});
});
cloudcode : add child role to parent ... sample working code but maybe not your best implementation... its parse/backbone/marionette impl.
Parse.Cloud.define("addrole", function(request, response) {
var roleParent = request.params.parentName;
var roleChild = request.params.childName.trim();
var _role , _chrole;
var _error = {
};
var _errorch = {
};
var _errorparm = {
};
var cst = {
parent:"parent",
pid:"pid",
child:"child"
};
if(roleParent == roleChild)response.error(_errorparm);
var cst1 = "parnt";
var qp = new Parse.Query(Parse.Role);
qp.equalTo("name", roleParent);
var qc = new Parse.Query(Parse.Role);
qc.equalTo("name", roleChild);
Parse.Cloud.useMasterKey();
qp.first().then(function(role) {
_role = role;
if (typeof _role === "undefined") {
return Parse.Promise.error(_error);
} else {
cst.parent = _role.get("name");
cst.pid = _role.get("objectId");
return qc.first();
};
}
).then(function(rolechld) {
_chrole = rolechld;
if (typeof _chrole === "undefined") {
return Parse.Promise.error(_errorch);
} else {
cst.child = _chrole.get("name");
console.log(cst);
_role.getACL().setRoleReadAccess(_chrole, true);
_role.getRoles().add(_chrole);
return _role.save();
}
}).then(function(hello) {
response.success(_chrole.toJSON());
}, function(error) {
response.error(error);
});
});
Related
I don't know if it is React.JS , or just me forgetting something with promises but I'm getting this error
const promise = SAIIndexedDB(response.data)
promise.then(function(result){
this.setState({
loadingMedications: false
});
})
.catch(function(error){
console.log('error', error);
});
Error:
TypeError: Cannot read property 'then' of undefined
line number shows it is this line promise.then(function(result){
I was reading through this and it seems correct...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
Reason I want/need a promise is that loadingMedications gets set to false which closes the spinner when the data is done loading from the function call SAIIndexedDB(..)
Here is the function that is calls
export function SAIIndexedDB(customerData){
var status = "start in helpers";
const dbName = "SAIOffline";
var request = indexedDB.open(dbName, 2);
request.onerror = function(event) {
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("medications", { keyPath: "value"});
objectStore.createIndex("short_description", "short_description", { unique: false });
//objectStore.createIndex("email", "email", { unique: true });
objectStore.transaction.oncomplete = function(event) {
// Store values in the newly created objectStore.
var customerObjectStore = db.transaction("medications", "readwrite").objectStore("medications");
customerData.forEach(function(customer) {
customerObjectStore.add(customer);
});
status = "done"
return status;
};
};
}
Please update your code like the followings:
SAIIndexedDB(response.data).then(function(result){
this.setState({
loadingMedications: false
});
})
.catch(function(error){
console.log('error', error);
});
export function SAIIndexedDB(customerData){
return new Promise((resolve, reject) => {
var status = "start in helpers";
const dbName = "SAIOffline";
var request = indexedDB.open(dbName, 2);
request.onerror = function(event) {
reject(event)
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("medications", { keyPath: "value"});
objectStore.createIndex("short_description", "short_description", { unique: false });
//objectStore.createIndex("email", "email", { unique: true });
objectStore.transaction.oncomplete = function(event) {
// Store values in the newly created objectStore.
var customerObjectStore = db.transaction("medications", "readwrite").objectStore("medications");
customerData.forEach(function(customer) {
customerObjectStore.add(customer);
});
status = "done"
resolve(status);
};
};
}
}
I am new to node.js and Javascript.
I have two javascript files "FabricUserController.js" and "UserController.js". So I have create the class in "FabricUserController.js" and export it into "UserController.js".
I am integrate the GetAll fucntion of "FabricUserController.js" to "UserController.js" in GetAllProduce fucntion.
I am trying run the below code however its giving me "TypeError: FabricUserControllers is not a constructor" error which is not handle in try catch{} block
Please see below code
let FabricUserControllers3 = require("./FabricUserController");
GetAllProduce: function (req, res, next) {
try{
let output = {};
var resArray = new Array();
let VZID = req.body.username;
console.log('test', 'GetAllProduce')
console.log('USername', VZID)
MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
if (err) {
let connError = new Error(500, "Error connecting to TEST database", err);
res.status(connError.status).json(connError);
} else {
let query = {};
client.db(config.Database.TEST.dbName).collection("Produce").find(query).toArray(function (err, response) {
console.log(response);
if (err) {
let roleError = new Error(500, "Error getting Produce information", err);
res.status(500).json(roleError);
} else if (response.length > 0) {
//DO someting here
//FabricUserControllers3 = {};
FabricUserControllers3 = new FabricUserControllers();// getting issue here
FabricUserControllers3.GetAll((VZID), (response) => {
console.log("data result", result)
res.status(200).json(response);
client.close();
})
} else {
output.message = "Produce doesn't exist";
res.status(409).json(output);
client.close();
}
});
}
});
}catch(e){
if (e instanceof TypeError){
console.log('error1', e.message);
printError(e,true);
}else{
console.log("error2", e.message);
printError(e, false);
}
}
},
FabricUserController.js
'use strict';
const {
FileSystemWallet,
Gateway
} = require('fabric-network');
const fs = require('fs');
const path = require('path');
var MongoClient = require('mongodb').MongoClient;
var Client = require('node-rest-client').Client;
var client = new Client();
const configPath = path.resolve(__dirname, '..', 'config', 'Config.json');
const configJSON = fs.readFileSync(configPath, 'utf8');
const config1 = JSON.parse(configJSON);
var connection_file = config1.connection_file;
var appAdmin = config1.appAdmin;
var gatewayDiscovery = config1.gatewayDiscovery;
var appAdminSecret = config1.appAdminSecret;
var orgMSPID = config1.orgMSPID;
var caName = config1.caName;
const ccpPath = path.resolve(__dirname, '..', 'config', 'connection.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
let response = {};
class FabricUserControllers {
constructor() {
console.log("constructer called")
}
async ProduceRegistration(Username, produceid, callback) {
// Create a new file system based wallet for managing identities.
try {
const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
setTimeout(() => {
cb();
resolve();
}, timeout);
});
let query2 = {}
query2.PRODUCEID = produceid;
// console.log('PRODUCEID',produceid)
var PRODUCE = {};
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
console.log('Username', Username)
// Check to see if we've already enrolled the user.
const userExists = await wallet.exists(Username);
if (!userExists) {
console.log('An identity for the user: ' + Username + ' does not exist in the wallet');
console.log('call the registerUser before retrying');
response.data = null;
response.httpstatus = 400;
response.message = `An identity for the ${Username} does not exist in the wallet`;
return response;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccpPath, {
wallet,
identity: Username,
discovery: {
enabled: false,
asLocalhost: true
}
});
///
MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
if (err) {
// let connError = new Error(500, "Error connecting to TEST database", err);
response.data=null;
response.httpstatus = 500;
response.message = "Error connecting to TEST database :" + err;
// res.status(connError.status).json(connError);
return response;
} else {
client.db(config.Database.TEST.dbName).collection("Produce").find(query2).toArray(function (err, docs) {
if (err) {
response.httpstatus = 500;
response.message = "Error with DB :" + err;
return response;
}
else{
console.log("blockchain_status", docs[0].blockchain_status)
console.log('Role name DB',docs);
console.log('Role name DB1',docs[0]);
if(docs[0].STATUS)
PRODUCE.produceid = docs[0].PRODUCEID;
PRODUCE.produceName = docs[0].PRODUCE;
PRODUCE.farmLocation = docs[0].FARMLOCATION;
PRODUCE.plantingDate = docs[0].PLANTINGDATE;
PRODUCE.harvestDate = docs[0].HARVESTDATE;
PRODUCE.status = docs[0].STATUS;
PRODUCE.produceQuantites = docs[0].VARIETY;
PRODUCE.gapInfo = docs[0].GAP;
PRODUCE.farmerID = docs[0].farmerID;
console.log('Produce', PRODUCE);
const doStuffAsync = async () => {
setAsyncTimeout(async () => {
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('dfarmchannel');
// Get the contract from the network.
const contract = network.getContract(config1.chaincodeName);
var args = JSON.stringify(PRODUCE)
console.log("type of arg", typeof (args));
// Submit the specified transaction.
// console.log('produceID', args.produceID);
if(args==null || args==''){
console.log('Server not responding please try again');
}else
{
const result = await contract.submitTransaction('ProduceRegistration', args);
var argsJson = JSON.parse(result)
// console.log('result', argsJson)
// console.log('result1', result)
if(argsJson.produceID !="" && argsJson.produceID !=null && argsJson.produceID !="undefined" && argsJson.produceID !=undefined){
// // return false;
response.data = result
response.httpstatus = 200;
response.message = `Transaction has been submitted ansd successfull with Result :${result}`;
return callback(response);
// console.log('result before', response);
// console.log('Transaction has been submitted ansd successfull with Result :' + result);
}else{
console.log('blockchain server not responed')
// return false
response.httpstatus = 500;
response.message = `Please enter produce ID :`;
return response;
}
}
}, 4000);
};
doStuffAsync();
}
client.close();
})
}
})
await gateway.disconnect();
}
catch (error) {
// if(error) throw error;
response.error = error;
response.httpstatus = 500;
response.message = "Failed to enroll admin due to above error";
return response;
}
};
}
module.exports = FabricUserControllers;
#Abhirock, on your main file you have:
let FabricUserControllers3 = require("./FabricUserController");
FabricUserControllers3 = new FabricUserControllers();// getting issue here
You are trying to override FabricUserControllers3 creating a new object FabricUserControllers but you are not importing it. Try next solution to see if it solves your problem:
const FabricUserController = require("./FabricUserController");
const fabricUserControllers3 = new FabricUserController();
Hope it helps :))
I am trying to implement Browser Push Notification for my website. I am noticing even though the browser received notification, it doesn't display the notification sometimes.
var showNotification = function (event, data) {
var notificationData = data['data'];
var title = notificationData['title'];
var body = notificationData['body'];
var icon = notificationData['icon'];
var notificationActionsData = notificationData["actions"];
var actions = [];
if(notificationActionsData) {
for(var i=0; i < notificationActionsData.length; i++) {
var action = {
action: "action" + i,
title: notificationActionsData[i].title,
};
actions.push(action);
}
}
var campaignId = notificationData["id"];
self.registration.showNotification(title, {
body: body,
icon: icon,
data: notificationData,
tag: notificationData.id,
actions: actions
});
pushowlReporting.tickle(campaignId, "delivery");
};
function processNotification(event) {
if (event.data) {
var data = event.data.json();
showNotification(event, data);
}
else {
fetch("https://" + hostname + "/api/v1/subdomain/" + subdomain + "/campaign/", {'mode': 'no-cors'}).then(
function (response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ', response.status);
return;
}
// Examine the text in the response
response.text().then(function (responseText) {
var data = JSON.parse(responseText);
showNotification(event, data);
});
}
).catch(function (err) {
console.log('Fetch Error :', err);
}
);
}
}
self.addEventListener('push', function (event) {
event.waitUntil(processNotification(event));
});
My reporting API shows that the notification has been delivered however the browser displays the notification intermittently.
The notification display is quite erratic. Sometimes the notifications will display immediately, while sometimes it doesn't display for a while and all of a sudden all past notifications come in a batch. And at times some notifications don't get displayed at all.
Let me know if am doing something wrong here?
Function passed to event.waituntil should return a promise. If not the scope would be messed up as the lifetime of the event wouldnt have got extended.
https://developer.mozilla.org/en-US/docs/Web/API/ExtendableEvent/waitUntil
var showNotification = function (event, data) {
var notificationData = data['data'];
var title = notificationData['title'];
var body = notificationData['body'];
var icon = notificationData['icon'];
var notificationActionsData = notificationData["actions"];
var actions = [];
if(notificationActionsData) {
for(var i=0; i < notificationActionsData.length; i++) {
var action = {
action: "action" + i,
title: notificationActionsData[i].title,
};
actions.push(action);
}
}
var campaignId = notificationData["id"];
return self.registration.showNotification(title, {
body: body,
icon: icon,
data: notificationData,
tag: notificationData.id,
actions: actions
}).then(function (succ) {
pushowlReporting.tickle(campaignId, "delivery");
});
};
function processNotification(event) {
if (event.data) {
var data = event.data.json();
return showNotification(event, data);
}
else {
return fetch("https://" + hostname + "/api/v1/subdomain/" + subdomain + "/campaign/", {'mode': 'no-cors'}).then(
function (response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ', response.status);
return;
}
// Examine the text in the response
response.text().then(function (responseText) {
var data = JSON.parse(responseText);
showNotification(event, data);
});
}
).catch(function (err) {
console.log('Fetch Error :', err);
}
);
}
}
I have just added return statements to your code. Try this out.
I'm creating a simple to-do list app with angular and cannot seem to figure out this strange bug. When the page loads initially, if I add tasks to my to-do list, then try to delete one the whole list disappears. However, if I don't refresh and add more task, they will delete individually afterwards. Can someone help me figure out what I'm missing?
Factory:
//Save user in local storage
AccountFactory.saveUser = function (user) {
var users = getUsers();
var index = this.getUser(user.email, 'index');
users[index] = user;
localStorage.setItem('Users', JSON.stringify(users));
return { status: 200, message: 'User saved', data: user };
};
AccountFactory.setCurrentUser = function (user) {
localStorage.setItem('currentUser', JSON.stringify(user));
return { status: 200, message: 'Current user set', data: user };
};
//Delete Task
AccountFactory.removeTask = function (user, task) {
var index = user.tasks.indexOf(task);
user.tasks.splice(index, 1);
return this.saveUser(user);
}
//Get all users function
function getUsers() {
var users = JSON.parse(localStorage.getItem('Users')) || [];
return users;
}
//Get user function
AccountFactory.getUser = function (email, type) {
var users = getUsers();
var account,
index;
for (var i = 0, user; user = users[i]; i++) {
if (user.email.toLowerCase() === email.toLowerCase()) {
account = user;
index = i;
break;
}
}
if (type === 'account') return account;
if (type === 'index') return index;
};
Controller:
function saveUser(user) {
var response = AccountFactory.saveUser(user);
if (response.status === 200) {
var newUser = new User(response.data);
AccountFactory.setCurrentUser(user);
$scope.user = user;
console.log(response.message);
}
}
$scope.removeTask = function (task) {
var response = AccountFactory.removeTask($scope.user, task);
saveUser(user);
}
A user is logged in to the website and tries to create a post. Whenever a new post is created, this post gets associated with the user who created the post.
Referring to a thinkster.io Tutorial, which uses older API of AngularFire.
When using AngularFire API v0.8.0, this line of code which adds the post breaks:
user.$child('posts').$child(postId).$set(postId);
The Post Factory (post.js) with the method for creating post is:
app.factory('Post',
function ($firebase, FIREBASE_URL, User) {
var ref = new Firebase(FIREBASE_URL + 'posts');
var posts = $firebase(ref).$asArray();
var Post = {
all: posts,
//Starting of create function
create: function (post) {
if (User.signedIn()) {
var user = User.getCurrent(); //Gets the current logged in user
post.owner = user.username;
return posts.$add(post).then(function (ref) {
var postId = ref.name();
user.$child('posts').$child(postId).$set(postId);
//user.$getRecord('posts').$getRecord(postId).$set(postId);
return postId;
});
}
},
//End of create function
Changelog for AngularFire states that
$child() no longer exists. The data already exists in the parent object and creating additional synchronized children is not efficient and discouraged. Use data transformations, flatten your data, or drop down to the Firebase SDK and use its child() method.
I am confused as to how to change the code to work with the update in the API.
After Edit
This is the getCurrent method:
getCurrent: function(){ // retrieves current user
return $rootScope.currentUser;
},
Which belongs to user.js Factory:
'use strict';
app.factory('User', function ($firebase, FIREBASE_URL, Auth, $rootScope) {
var ref = new Firebase(FIREBASE_URL + 'users');
var users = $firebase(ref);
var usersdiv = $firebase(ref).$asArray();
var User = {
create: function (authUser, username) {
users[username] = {
md5_hash: authUser.md5_hash,
username: username
};
users.$update(username, {
md5_hash: authUser.md5_hash,
username: username
}).then(function (dataRef) {
dataRef.setPriority(authUser.uid);
setCurrentUser(username);
});
}, // end of create method
findByUsername: function(username){
if(username){
return usersdiv.$getRecord(username);
}
},
getCurrent: function(){ // retrieves current user
return $rootScope.currentUser;
},
signedIn: function(){ //checks if user is signed in
return $rootScope.currentUser !== undefined;
}
}; // end of User
// so that we can pull info about user when logged in
function setCurrentUser (username){
$rootScope.currentUser = User.findByUsername(username);
}
//for logins and refreshes
$rootScope.$on('$firebaseSimpleLogin:login', function(e, authUser){
var queryRef = ref.startAt(authUser.uid).endAt(authUser.uid);
var queryArray = $firebase(queryRef).$asArray();
queryArray.$loaded().then(function() {
setCurrentUser(queryArray.$keyAt(0));
});
});
//logout
$rootScope.$on('$firebaseSimpleLogin:logout', function(){
delete $rootScope.currentUser;
});
return User;
});
You don't need to create a synchronized object locally (what $child used to do) just to set a value in Firebase. You can do this at any time with the Firebase ref you've already created. I can't tell exactly what the data structure of user is since it wasn't included, but something like this:
new Firebase(FIREBASE_URL).child('...path/to/posts').child(postId).set(postId);
Most likely, this belongs on your user object, so that in the Post factory, you can just do something like user.addPost(postId).
I was facing the same problem. As Kato suggested, you will have to use the child function in the Firebase object. I chose to add the post to the user in the Post factory itself.
Adding Post to User
var usersref = new Firebase(FIREBASE_URL + 'users');
usersref.child(post.owner).child('posts').child(postId).set(postId);
The Entire post.js is as below:
'use strict';
app.factory('Post',
function($firebase, FIREBASE_URL, User){
var ref = new Firebase(FIREBASE_URL + 'posts');
var usersref = new Firebase(FIREBASE_URL + 'users');
var posts = $firebase(ref).$asArray();
var Post = {
all : posts,
create : function(post){
if(User.signedIn()){
var user = User.getCurrent();
post.owner = user.username;
return posts.$add(post).then(function(ref){
var postId = ref.name();
usersref.child(post.owner).child('posts').child(postId).set(postId);
return postId;
});
}
},
find: function(postId){
return $firebase(ref.child(postId)).$asObject();
},
delete: function(postId){
if(User.signedIn()){
var postToDel = Post.find(postId);
postToDel.$loaded().then(function(){
var p = posts[postToDel.$id];
posts.$remove(postId).then(function(){
$firebase(usersref.child(p.owner).child('posts')).$asArray().$remove(p.$id);
});
});
}
}
};
return Post;
});
Correct Answer is:
'use strict';
app.factory('Post',
function ($firebase, FIREBASE_URL, User) {
var postsref = new Firebase(FIREBASE_URL + 'posts');
var usersref = new Firebase(FIREBASE_URL + 'users');
var posts = $firebase(postsref).$asArray();
var Post = {
all: posts,
create: function (post) {
if (User.signedIn()) {
var user = User.getCurrent();
post.owner = user.username;
return posts.$add(post).then(function (ref) {
var postId = ref.name();
//a child in user forge should be made with its key as postID
usersref.child(post.owner).child('posts').child(postId).set(postId);
return postId;
});
}
},
find: function (postId) {
return $firebase(postsref.child(postId)).$asObject();
},
delete: function (postId) {
if (User.signedIn()) {
var postToDel = Post.find(postId);
postToDel.$loaded().then(function(){
var p = posts[postToDel.$id];
posts.$remove(postId).then(function(){
$firebase(usersref.child(p.owner).child('posts')).$remove(p.$id);
});
});
}
},
Thus, child can be used at Firebase SDK Level.
Example:
var ref = new Firebase(FIREBASE_URL);
var userArray = $firebase(ref.child('user')).$asArray();
var userObject = $firebase(ref.child('user')).$asObject();