JSONStore events not firing - ibm-mobilefirst

I have tried this many, many ways over the last week, but I cannot get the JSONStore callbacks to fire consistently. I'm working on a Mac running Worklight 5.0.6. I'll provide what I think is the most simple example: code created from the Worklight JSONStore generator with hard-coded values.
After initializing the collections and calling a function like findAll() neither the success nor the failure callbacks are triggered. I have had the callbacks work, but not consistently or reliably. I cannot explain why it mostly doesn't work.
I have tried this both using the jQuery promise framework and the deprecated callback methods. In both cases the callbacks aren't getting called. I have also tried calling destroy() on the JSONStore to force fresh creation.
function initContactsCollection() {
if ((WL.Client.getEnvironment() === 'iphone' ||
WL.Client.getEnvironment() === 'ipad' ||
WL.Client.getEnvironment() === 'android') &&
typeof cordova !== 'undefined' &&
typeof WL.JSONStore !== 'undefined' &&
typeof jQuery !== 'undefined' &&
typeof jQuery.event.trigger === 'function') {
// var pwd = prompt('Enter your password');
var contacts = WL.JSONStore.initCollection("contacts",
{"agentId":"string","notes.isSuccessful":"boolean","firstName":"string","workPhone":"string","email1":"string","email2":"string"},
{
//password: pwd,
adapter : {
name: 'ams',
replace: 'updateContact',
remove: 'deleteContactNote',
add: 'addNewContact',
load: {
procedure: 'getContacts',
params: ["AA12345678910X-DB"],
key: 'contacts'
},
accept: function (data) {
return (data.status === 200);
}
}
});
contacts.promise
.done(function () {
WL.Logger.debug('[JSONStore] contacts is ready to be used.');
contacts.count().done(function(res){
if(res < 1){
customers.load();
}
});
})
.fail(function (errObj) {
WL.Logger.debug('[JSONStore]' + errObj.toString());
});
} else {
WL.Logger.debug('[JSONStore] Check your dependencies.');
}
} // end function

There are a number of errors in your JavaScript, you're calling customers.load instead of contacts.load, and the nesting of promises that you have, probably isn't what you want. I don't have your adapter so I can't make 100% sure this code works, but it'll be much close to what you want.
function initContactsCollection() {
if ((WL.Client.getEnvironment() === 'iphone' ||
WL.Client.getEnvironment() === 'ipad' ||
WL.Client.getEnvironment() === 'android') &&
typeof cordova !== 'undefined' &&
typeof WL.JSONStore !== 'undefined' &&
typeof jQuery !== 'undefined' &&
typeof jQuery.event.trigger === 'function') {
// var pwd = prompt('Enter your password');
var contacts = WL.JSONStore.initCollection("contacts",
{"agentId":"string","notes.isSuccessful":"boolean","firstName":"string","workPhone":"string","email1":"string","email2":"string"},
{
//password: pwd,
adapter : {
name: 'ams',
replace: 'updateContact',
remove: 'deleteContactNote',
add: 'addNewContact',
load: {
procedure: 'getContacts',
params: ['AA12345678910X-DB'],
key: 'contacts'
},
accept: function (data) {
return (data.status === 200);
}
}
});
contacts.promise
.then(function () {
WL.Logger.debug('[JSONStore] contacts is ready to be used.');
return contacts.count();
})
.then(function(res){
var newDeferred;
if(res < 1){
WL.Logger.debug('DB Empty, calling load');
return contacts.load();
}else{
newDeferred = $.Deferred();
setTimeout(function(){
newDeferred.resolve(0);
});
return newDeferred;
}
})
.then(function(){
WL.Logger.debug('done with setup stuff');
})
.fail(function (errObj) {
WL.Logger.debug('[JSONStore]' + errObj.toString());
});
} else {
WL.Logger.debug('[JSONStore] Check your dependencies.');
}
} // end function

Related

How to redirect all paths except two if a condition is not met in Express

On my express server I'am tring to implement the following logic:
If the path is not /Login or /Register
And the request.session.authenticated is not true.
Redirect all request to /Login.
In other words , pseudocode :
function()
{
if (req.session.authenticated !== true && path !== '/Login')
res.redirect('/Login')
}
How can i write this function in Express with app.get() or similar ?
app.get( path , (req, res) =>
{
// ??
})
------------------------------------------- After edited --------------------------
So , I tried this :
app.use(redirect())
function redirect(req, res, next)
{
if (req.session.authenticated !== true && req.path !== '/Login/Login.html' || req.session.authenticated !== true && req.path !== '/Register/Register.html')
{
res.redirect('/Login/Login.html');
return next()
}
}
But , I got the following error :
if (req.session.authenticated !== true && req.path !== '/Login/Login.html' || req.session.authenticated !== true && req.path !== '/Register/Register.html')
^
TypeError: Cannot read property 'session' of undefined
I guess that for some reason this function does not have acess to the request object which is weird. How can I make it acess the request ? I thought all middleware functions would have acess to the request.
------------------------------------2nd Edit------------------------------------
In my case the middleware function above only works if you save it to a variable and then use app.use() calling the variable the function was saved in.
So that would be :
app.use(redirectMe)
let redirectMe = function redirect(req, res, next)
{
if (req.session.authenticated !== true && req.path !== '/Login/Login.html' || req.session.authenticated !== true && req.path !== '/Register/Register.html')
{
res.redirect('/Login/Login.html');
return next()
}
}
You can write something like an authentication middleware for this.
function redirect(req, res, next) {
if (req.session.authenticated !== true && req.path !== '/Login' && req.path !== '/Register') {
res.redirect('/Login');
return
}
}
And the you just need to export that function and you can use it as a middleware in your routes. Something like this:
app.get('/profile', redirect(), (req, res) => {
//Some code here
});
Declare a function in a golobal variable as shown below
let verifyLogin = (req, res,next){
if(req.session.authenticated)
{
next()
} else {
res.redirect('/login')
}
}
The above function is called from app.get() as shown below
app.get('path', verifyLogin, (req, res)=>{
//
})

Computed value stops reacting after the first change in the state

In my component, I have showTrigger computed property and saveDataToStore method that does the update.
computed: {
showTrigger() {
if (typeof store.getters["applicationBuilder/getTriggerById"](this.id) === "undefined") {
return false;
}
return store.getters["applicationBuilder/getTriggerById"](this.id).show;
}
},
methods: {
saveDataToStore(info) {
const trigger = {
id: this.id,
type: this.selected.type,
info: info,
show: false
};
store.dispatch('applicationBuilder/updateTriggerById', trigger);
}
}
My store file:
const state = {
triggers: []
};
const getters = {
getTriggerById: (state) => (id) => {
return state.triggers.find(trigger => trigger.id === id)
}
};
const actions = {
updateTriggerById({commit}, payload) {
commit('mutateTriggerById', payload);
}
};
const mutatations = {
mutateTriggerById(state, payload) {
let index = state.triggers.findIndex(trigger => trigger.id === payload.id)
state.triggers[index].id = payload.id;
if (typeof payload.type !== "undefined") {
state.triggers[index].type = payload.type;
}
if (typeof payload.info !== "undefined") {
state.triggers[index].info = payload.info;
}
if (typeof payload.show !== "undefined") {
state.triggers[index].show = payload.show;
}
}
};
When I initially set the element in array showTrigger picks up the change. But every next change to show property of the trigger array is not firing get in computed value.
Do I have to change how I initiate the array. It doesn't help when I set default values for array in a state like this:
triggers: [
{
id: null,
show: false,
info: {},
type: null
}
],
What am I doing wrong?
After testing your code, I think changing the mutation to add the payload in the first time solves the issue and the computed property started updating every time:
const mutations = {
mutateTriggerById(state, payload) {
let index = state.triggers.findIndex(
(trigger) => trigger.id === payload.id
);
if(state.triggers[index]) {
state.triggers[index].id = payload.id;
if (typeof payload.type !== "undefined") {
state.triggers[index].type = payload.type;
}
if (typeof payload.info !== "undefined") {
state.triggers[index].info = payload.info;
}
if (typeof payload.show !== "undefined") {
state.triggers[index].show = payload.show;
}
}else{
state.triggers.push(payload);
}
}
};

How to subscribe multiple observable in rxjs 6 ? do is not a function in rxjs 6

In rxjs 5.5.12, I created a login() to subscribe with multiple observable by do()
login(userEmail, userPassword).subscribe((response) => {
console.log(response);
if (response === 'something') {
// some actions
} else {
// some actions
}
},(error) => {
// some error actions
});
I use rxLoginPOST to call api:
rxLoginPOST(url, params) {
return Rx.Observable.fromPromise(somePromise).catch(handleErrFunction);
}
I use it in login function it return multiple observable:
login(email, password) {
return APIService.shared.rxLoginPOST('users/signin', { ...arguments })
.flatMap((response) => {
if (response.status === 200) {
return Rx.Observable.combineLatest(
myObservable1,
myObservable2,
myObservable3
)
} else {
return Rx.Observable.of(response)
}
}).do((result) => {
if (result.length > 0) {
// some logic
} else {
return Rx.Observable.of(result)
}
}).flatMap((result) => {
if (result.length > 0) {
return this.checkUserIsRegistered()
} else {
return Rx.Observable.of(result)
}
})
}
In rxjs 6.5.3, I had changed all the import like
import { Observable, combineLatest, of } from 'rxjs';
import { mergeMap, map, catchError, flatMap, tap } from 'rxjs/operators';
If I trigger login() it will show do is not a function
So I change the code:
login(userEmail, password) {
return APIService.shared.rxLoginPOST('users/signin', { ...arguments }).pipe(
mergeMap((response) => {
if (response.status === 200) {
return combineLatest(
myObservable1,
myObservable2,
myObservable3
)
} else {
return of(response)
}
}).tap((result) => { // I am stuck here, I have no idea how to continue with it...
console.log('check 4'); // check 4 does not appear.
console.log('response', response);
return of(response)
}
);
I try to use tap instead of do, but check 4 does not appear.
Any help would be appreciated.
With pipe, you should chain your operators like this: pipe(op1, op2) and not like pipe(op1).op2()
login(userEmail, password) {
return APIService.shared.rxLoginPOST('users/signin', { ...arguments })
.pipe(
mergeMap((response) => {
if (response.status === 200) {
return combineLatest(
myObservable1,
myObservable2,
myObservable3
)
}
return of(response)
}),
tap((result) => {
console.log('check 4'); // check 4 does not appear.
console.log('response', response);
})
);
I also removed your useless else statement since you are returning something before :)
EDIT: As suggested in comments, the return instruction from tap has also been removed since unecessary

Vuevalidate async validation results to a loop

Am using Vue Validate
i have the following in my vuevlidate
validations: {
user_form: {
email: {required,email, isUnique(value) {
// standalone validator ideally should not assume a field is required
if (value === '') return true;
// simulate async call, fail for all logins with even length
return new Promise((resolve, reject) => {
this.$http.post("v1/user-management/users/email-registeredi",{email:value}).then((res)=>{
console.log("res is ", res);
resolve(true);
},(err)=>{
reject(false)
})
})
}},
role: {required},
password: {required}
}
},
The above creates an endless loop of http requests especially when it gets an error
Where am i going wrong
In case vue validate is not handling reject promise well and creating infinite loop.
You can try, async await for Vue validate's isUnique with try and catch returning false on error,
something like this.
validations: {
user_form: {
email: {
required,
email,
async isUnique (value) {
if (value === '') return true
try{
const response = await this.$http.post("v1/user-management/users/email-registeredi",{email:value})
return true;
}
catch(e){
return false;
}
}
}
}
You don't need to use "new Promise" because vue-resource already do that. Try this:
validations: {
user_form: {
email: {required,email, isUnique(value) {
// standalone validator ideally should not assume a field is required
if (value === '') return true;
// simulate async call, fail for all logins with even length
return this.$http.post("v1/user-management/users/email-registeredi",{email:value}).then((res)=>{
console.log("res is ", res);
return true;
},(err)=>{
return false;
});
}},
role: {required},
password: {required}
}
},

VueJs this.method is not a function? How to call a method inside another method in Vuejs?

I'm trying to call a method from another method and for this I've used this. But my console is causing me an error.
How to call a method inside another method in Vuejs?
code
methods: {
searchLocations: function() {
var address = this.search
var geocoder = new window.google.maps.Geocoder()
geocoder.geocode({
address: address
}, function(results, status) {
if (status === window.google.maps.GeocoderStatus.OK) {
this.buscarLojas(results[0].geometry.location)
}
})
},
buscarLojas: function(center) {
console.log(center)
}
}
console:
this.buscarLojas is not a function
You have an anonymous call back function that overwrites this keyword, you can either assign this to another variable ref before using it in your anonymous function:
methods: {
searchLocations: function () {
var address = this.search
var geocoder = new window.google.maps.Geocoder()
var ref = this
// ^^^^^^^^^^^^^^
geocoder.geocode({address: address}, function (results, status) {
if (status === window.google.maps.GeocoderStatus.OK) {
ref.buscarLojas(results[0].geometry.location)
//^^^
} else {
alert(address + ' not found')
}
})
},
buscarLojas: function (center) {
console.log(center)
}
}
Or use an arrow function:
methods: {
searchLocations: function () {
var address = this.search
var geocoder = new window.google.maps.Geocoder()
geocoder.geocode({address: address}, (results, status) => {
// ^^
if (status === window.google.maps.GeocoderStatus.OK) {
this.buscarLojas(results[0].geometry.location)
} else {
alert(address + ' not found')
}
})
},
buscarLojas: function (center) {
console.log(center)
}
}
Use arrow function for callback
geocoder.geocode({address: address}, (results, status) => {
if (status === window.google.maps.GeocoderStatus.OK) {
this.buscarLojas(results[0].geometry.location)
}
})
I know there is an answer here already, but this can also be a convenient alternative
methods: {
var self = this; //this line will take control of **this** which can be use later
searchLocations: function() {
var address = self.search
var geocoder = new window.google.maps.Geocoder()
geocoder.geocode({
address: address
}, function(results, status) {
if (status === window.google.maps.GeocoderStatus.OK) {
self.buscarLojas(results[0].geometry.location)
}
})
},
buscarLojas: function(center) {
console.log(center)
}
}