Call says cannot read property 'then of undefined (looks valid ) - javascript

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);
};
};
}
}

Related

Problem with function not finishing because of async?

The code inside the comment block does not work, if I put it inside an if statement.
I think the main issue is that it happens to be before a return statement, so how can I make sure it finishes running before return is initiated.
I've tried let {cool} = await .... with no luck
The intent is to copy and paste the code from above to inside the if statement.
var AWS = require("aws-sdk");
AWS.config.region = "us-east-1";
var lambda = new AWS.Lambda();
exports.handler = async (event) => {
////----------------------------THIS CODE HERE WORKS-------------------------------------------///////
var PayloadObj = {
amount: String(event["amount"]),
email: String(event["email"]),
};
var Payload = JSON.stringify(PayloadObj);
var params = {
FunctionName: "lambda-2", // the lambda function we are going to invoke
Payload: Payload,
};
let { cool } = lambda.invoke(params, function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data.Payload);
}
});
//-------------------------------------END of this CODE --------------------------------------////
// TODO implement
const stripe = require("stripe")("sk_test");
var amount = event["amount"];
var token = event["token"];
let { status } = await stripe.charges.create({
amount: amount * 100,
currency: "usd",
description: amount,
source: token,
});
if (status === "succeeded") {
//--------------------------------Same code here!-------------------------------///
// same code from above
//---------------------------Does not work!!------------------------------------------//
const response = {
statusCode: 200,
body: JSON.stringify(status),
};
return response;
} else {
const response = {
statusCode: 402,
body: JSON.stringify("Payment Failed"),
};
return response;
}
};
If you are using await, you don't need to use call back function to display data and error. You can just use try-catch block.
var PayloadObj = {
amount: String(event["amount"]),
email: String(event["email"]),
};
var Payload = JSON.stringify(PayloadObj);
var params = {
FunctionName: "lambda-2", // the lambda function we are going to invoke
InvocationType: "RequestResponse", // InvocationType: "Event",
Payload: Payload,
};
try{
const data = await lambda.invoke(params).promise();
console.log(data.payload);
}catch(err){
console.log(err);
}

Can't to add data to IndexedDB where is problem in my code?

I'm trying to put object to indexedDB. But no effect.
Connection is working, and created new table "info", but when I'm trying to put data nothing happens.
window.indexedDB = window.indexedDB || window.mozIndexedDB ||
window.webkitIndexedDB || window.msIndexedDB;
let db;
let request = window.indexedDB.open("InfoDB", 1);
request.onerror = function(e) {
console.log("Klaida: " + e.target.error);
};
request.onupgradeneeded = function(e) {
db = e.target.result;
let infoTB = db.createObjectStore("info", { autoIncrement : true });
objectStore.createIndex('data', 'data', { unique: false });
objectStore.createIndex('laikas', 'laikas', { unique: false });
};
function getData() {
let paketas = {
"data": manoData,
"laikas": {
manoLaikas: {
"vardas": manoVardas,
"telefonas": manoTelefonas,
"paslauga": manoPaslauga
}
}
}
request.onsuccess = function (e) {
db = e.target.result;
let tran = db.transaction(["info"], "readwrite");
let objektas = tran.objectStore("info");
objektas.add(paketas);
tran.oncomplete = function(e) {
console.log('pavyko');
};
}
}
I need that paketas content appear in info table.

How to create consumer for kafka topic?

I have topic created on kafka server now i am creating consumer to read topic messages from server, but i dont see any data when i try to consume message using consumer.on('message') , Any idea what is implemented wrong in below code , Do i need to set offset ?
consumer.js
var kafka = require('kafka-node');
var config = require('./config.js');
var zk = require('node-zookeeper-client');
var kafkaConn = config.kafkaCon.dit;
var HighLevelConsumer = kafka.HighLevelConsumer;
var Client = kafka.Client;
function start() {
topics = [{
topic: 'test-1'
}];
var groupId = 'push';
var clientId = "consumer-" + Math.floor(Math.random() * 10000);
var options = {
autoCommit: true,
fetchMaxWaitMs: 100,
fetchMaxBytes: 10 * 1024 * 1024,
groupId: groupId
};
console.log("Started consumer: ", clientId);
var consumer_client = new kafka.Client(kafkaConn, clientId);
var client = new Client(consumer_client.connectionString, clientId);
var consumer = new HighLevelConsumer(client, topics, options);
consumer.on('message', function(message) {
var topic = message.topic;
console.log('Message', topic);
});
};
start();
const Kafka = require("node-rdkafka");
const kafkaConf = {
"group.id": "cloudkarafka-example",
"metadata.broker.list": ["localhost:9092"],
"socket.keepalive.enable": true,
//"security.protocol": "SASL_SSL",
//"sasl.mechanisms": "SCRAM-SHA-256",
//"sasl.username": process.env.CLOUDKARAFKA_USERNAME,
//"sasl.password": process.env.CLOUDKARAFKA_PASSWORD,
"debug": "generic,broker,security",
'enable.auto.commit': false,
};
//const prefix = process.env.CLOUDKARAFKA_USERNAME;
const topics = ['topicName'];
const consumer = new Kafka.KafkaConsumer(kafkaConf, {
"auto.offset.reset": "beginning"
});
consumer.on("error", function(err) {
console.error(err);
});
consumer.on("ready", function(arg) {
console.log(`Consumer ${arg.name} ready`);
consumer.subscribe(topics);
consumer.consume();
});
consumer.on("data", function(m) {
console.log(m.value.toString());
});
consumer.on("disconnected", function(arg) {
process.exit();
});
consumer.on('event.error', function(err) {
console.error(err);
process.exit(1);
});
consumer.on('event.log', function(log) {
console.log(log);
});
consumer.connect();
A Kafka Consumer can be written with the kafka-node npm module. For my use case, my consumer was a separate Express server which listened to events and stored them in a database.
import kafka from "kafka-node"
const client = new kafka.Client("http://localhost:2181");
const topics = [
{
topic: "webevents.dev"
}
];
const options = {
autoCommit: true,
fetchMaxWaitMs: 1000,
fetchMaxBytes: 1024 * 1024,
encoding: "buffer"
};
const consumer = new kafka.HighLevelConsumer(client, topics, options);
consumer.on("message", function(message) {
// Read string into a buffer.
var buf = new Buffer(message.value, "binary");
var decodedMessage = JSON.parse(buf.toString());
//Events is a Sequelize Model Object.
return Events.create({
id: decodedMessage.id,
type: decodedMessage.type,
userId: decodedMessage.userId,
sessionId: decodedMessage.sessionId,
data: JSON.stringify(decodedMessage.data),
createdAt: new Date()
});
});
consumer.on("error", function(err) {
console.log("error", err);
});
process.on("SIGINT", function() {
consumer.close(true, function() {
process.exit();
});
});
more info in https://nodewebapps.com/2017/11/04/getting-started-with-nodejs-and-kafka/

How test Service working with IndexedDB in AngularJS

I have app in AngularJS, where I make services, which stores data to IndexedDb.
It's look like this:
var IndexedDbServices = angular.module('IndexedDbServices', []);
IndexedDbServices.factory('IndexedDb', ['$window', '$q', function($window, $q){
var indexedDB = $window.indexedDB;
var db=null;
var open = function() {
var deferred = $q.defer();
var version = 3;
var request = indexedDB.open("lCApp", version);
request.onupgradeneeded = function(e) {
db = e.target.result;
e.target.transaction.onerror = indexedDB.onerror;
if(db.objectStoreNames.contains("collections")) {
db.deleteObjectStore("collections");
}
var store = db.createObjectStore("collections", {
keyPath: "id", autoIncrement : true
});
store.createIndex("name", "name", { unique: true });
store.createIndex("description", "description", { unique: false });
store.transaction.oncomplete = function(event) {
var customerObjectStore = db.transaction("collections", "readwrite").objectStore("collections");
customerObjectStore.add({name: "coll1", description: "desc for coll1"});
customerObjectStore.add({name: "coll2", description: "desc for coll2"});
};
};
request.onsuccess = function(e) {
db = e.target.result;
deferred.resolve();
};
request.onerror = function(){
deferred.reject();
};
return deferred.promise;
};
var findAll = function() {
var deferred = $q.defer();
if(db === null || db === undefined) {
deferred.reject("IndexDB is not opened yet!");
} else{
var trans = db.transaction(["collections"], "readwrite");
var store = trans.objectStore("collections");
var data = [];
// Get everything in the store;
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(result === null || result === undefined)
{
deferred.resolve(data);
}
else{
data.push(result.value);
result.continue();
}
};
cursorRequest.onerror = function(e){
console.log(e.value);
deferred.reject("Something went wrong!!!");
};
}
return deferred.promise;
};
return {
open: open,
add: add,
findAll: findAll
};
}]);
And I want test this code using unit test (jasmine). So i wrote this:
describe('IndexedDB service', function() {
beforeEach(function() {
module('IndexedDbServices');
});
it('should open db and find 2 collections', inject(function(IndexedDb) {
IndexedDb.open().then(function(e){
console.log(e);
}, function(err){
$window.alert(err);
});
console.log(IndexedDb.findAll());
}));
});
Would you advise me how test if function open in IndexedDb service create IndexedDb and add rows. And next I function open in IndexedDB service return all that records?
I don't know why, but in this test db is not created console.log(IndexedDb.findAll()); print: Promise{$$state: Object{status: 2, value: 'IndexDB is not opened yet!'}}
So Db is not created.
And next how use expect(..).toEqual() or something this in returned promises?
Let's have the service:
/*global window: false */
'use strict';
angular.module('main')
.config(['$provide', function ($provide) {
$provide.constant('indexedDB', window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
}])
.service('idb', function idbService($q, $rootScope, indexedDB) {
var service = this;
var db;
service.open = function () {
console.log('idb.open');
var deferred = $q.defer();
var request = indexedDB.open('mydb', 1);
request.onupgradeneeded = function (e) {
console.log('idb.open onupgradeneeded');
db = e.target.result;
if (!db.objectStoreNames.contains('mystore')) {
db.createObjectStore('mystore', {
keyPath: 'id'
});
}
};
request.onsuccess = function (e) {
console.log('idb.open onsuccess');
db = e.target.result;
deferred.resolve();
$rootScope.$apply(); // Propagate promise resolution to 'then' functions using $apply().
};
request.onerror = function (e) {
console.log('idb.open onerror ', e);
deferred.reject();
};
return deferred.promise;
};
service.put = function (key, value) {
console.log('idb.put(' + key + ', ' + value + ')');
var deferred = $q.defer();
var store = db.transaction(['mystore'], 'readwrite').objectStore('mystore');
var request = store.put({
id: key,
data: value
});
request.onsuccess = function () {
console.log('idb.put onsuccess');
deferred.resolve();
$rootScope.$apply(); // Propagate promise resolution to 'then' functions using $apply().
};
request.onerror = function (e) {
console.log('idb.put onerror ', e);
deferred.reject(e);
};
return deferred.promise;
};
service.get = function (key) {
console.log('idb.get' + '(' + key + ')');
var deferred = $q.defer();
var store = db.transaction(['mystore'], 'readwrite').objectStore('mystore');
var request = store.get(key);
request.onsuccess = function (e) {
console.log('idb.get onsuccess ', e.target.result);
deferred.resolve(e.target.result.data);
$rootScope.$apply(); // Propagate promise resolution to 'then' functions using $apply().
};
request.onerror = function (e) {
console.log('idb.get onerror', e);
deferred.reject(e);
};
return deferred.promise;
};
});
Test can be:
'use strict';
describe('idb', function () {
beforeEach(module('main'));
var idb;
var idbOpened;
beforeEach(angular.mock.inject(function (_idb_) {
idb = _idb_;
}));
beforeEach(function (done) {
idbOpened = false;
console.log(1);
idb.open().then(function () {
console.log(3);
idbOpened = true;
done();
})
console.log(2);
});
it('opens', function () {
expect(idbOpened).toBe(true);
console.log(4);
});
it('gets the put', function (done) {
console.log(10);
idb.put('666', 'bob').then(function () {
console.log(12);
idb.get('666').then(function (value) {
console.log(13);
expect(value).toBe('bob');
done();
console.log(14);
})
})
console.log(11);
});
});
Test output would be then:
LOG: 1
LOG: 'idb.open'
LOG: 2
LOG: 'idb.open onsuccess'
LOG: 3
LOG: 4
LOG: 1
LOG: 'idb.open'
LOG: 2
LOG: 'idb.open onsuccess'
LOG: 3
LOG: 10
LOG: 'idb.put(666, bob)'
LOG: 11
LOG: 'idb.put onsuccess'
LOG: 12
LOG: 'idb.get(666)'
LOG: 'idb.get onsuccess ', Object{id: '666', data: 'bob'}
LOG: 13
LOG: 14
Ugly stuff is a need to call
$rootScope.$apply();
to propagate promise resolution to 'then' functions in the test, because
it is not needed for the service itself.

Create Parse.com Roles Programmatically

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);
});
});

Categories

Resources