I need yours help.
I have two .factory's in Services.js
The first .factory works with a database, the second .factory with e-mail, files and so on.
How to pass a value from first factory to second? How to select data from the first factory?
//first factory
angular.module('starter.services', ['ngCordova', 'ngSanitize', 'ngCsv'])
.factory('NotesDataService', function ($cordovaSQLite, $ionicPlatform) {
var db, dbName = "CONTACTS_DB"
function useWebSql() {
db = window.openDatabase(dbName, "1.0", "Contacts database", 200000)
console.info('Using webSql')
}
function useSqlLite() {
db = $cordovaSQLite.openDB({name: dbName, location : 1})
console.info('Using SQLITE')
}
function initDatabase(){
$cordovaSQLite.execute(db, 'CREATE TABLE IF NOT EXISTS T_CONTACTS (id integer primary key, nom, prenom, codePostale, ville, email, portable)')
.then(function(res){
}, onErrorQuery)
}
$ionicPlatform.ready(function () {
if(window.cordova){
useSqlLite()
} else {
useWebSql()
}
initDatabase()
})
function onErrorQuery(err){
console.error(err)
}
return{
getAll: function(callback){
$ionicPlatform.ready(function () {
$cordovaSQLite.execute(db, 'SELECT * FROM T_CONTACTS').then(function (results) {
var data = []
for (i = 0, max = results.rows.length; i < max; i++) {
data.push(results.rows.item(i))
}
callback(data)
}, onErrorQuery)
})
}})
//second factory, here I need to get data from first factory
//to create a text file with the data from the database
// and attach this file to the e-mail
.factory('ContactsService', function ($ionicPlatform, $cordovaEmailComposer, $cordovaSQLite, $cordovaFile, NotesDataService) {
$ionicPlatform.ready(function () {
initCordovaEmailComposer();
})
function initCordovaEmailComposer() {
$cordovaEmailComposer.isAvailable().then(function () {
//is available
alert('avaible');
}, function () {
//not available
alert('not available');
})
}
return {
createEmail: function () {
var email = {
to: 'test#gmail.com',
cc: 'test#gmail.com',
bcc: 'test#gmail.com',
attachments: [
'file://cordova.file.externalDataDirectory/contacts.txt',
],
subject: 'Cordova Icons',
body: "Hello, mon ami",
isHtml: true
};
$cordovaEmailComposer.open(email).then(null, function () {
});
},
debugMessage: function (data) {
console.log('debug message', data);
},
createFile: function () {
var fileContacts = document.addEventListener('deviceready', function () {
NotesDataService.getAll(function (data) {
console.log(data)
return data
})
console.log('file contacts in console: ',fileContacts)
var fileName = 'contacts.txt'
var fileText = fileContacts
var filePath = cordova.file.externalDataDirectory
//CHECK file
$cordovaFile.checkFile(filePath, fileName).then(function (success) {
alert("file exist")
}, function (error) {
alert("file not exist", filePath)
//WRITE NEW FILE
$cordovaFile.writeFile(cordova.file.externalDataDirectory, fileName, fileText, true).then(function (success) {
// success
}, function (error) {
// error
});
});
})
},
}
})
Thank you all for your advice and support
Inject these factories into one another :
.factory('NotesDataService',['$cordovaSQLite','$ionicPlatform','ContactsService', function ($cordovaSQLite, $ionicPlatform,ContactsService) ....
.factory('ContactsService',['$ionicPlatform',.....,'NotesDataService', function ($ionicPlatform, $cordovaEmailComposer, $cordovaSQLite, $cordovaFile, NotesDataService) {
Now you can use either factory variables and functions in other factory.
Related
I'm using the react native ble manager package to build a react native app that communicates with a python client over BLE.
When writing to a characteristic on Android (this bug does not seem to appear on IOS) the write is successful but shortly after it I receive this error:
ERROR Error writing eeee2a38-0000-1000-8000-00805f9b34fb status=14
This is the simplified code that handles connecting, notifications and writing on the Android side:
import { NativeModules, NativeEventEmitter, Platform } from 'react-native'
import BleManager, { Peripheral } from 'react-native-ble-manager'
import { END } from 'redux-saga'
import { bytesToString } from 'convert-string'
const UPDATE_SERVICE_UUID = '0000180d-aaaa-1000-8000-00805f9b34fb'
export const Characteristic =
{
WIFI_STATUS_UUID: 'bbbb2a38-0000-1000-8000-00805f9b34fb',
WIFI_CREDS_UUID: 'aaaa2a38-0000-1000-8000-00805f9b34fb',
VERSION_UUID: 'cccc2a38-0000-1000-8000-00805f9b34fb',
UPDATE_STATUS_UUID: 'dddd2a38-0000-1000-8000-00805f9b34fb',
DO_UPDATE_UUID: 'eeee2a38-0000-1000-8000-00805f9b34fb',
ERROR_UUID: 'ffff2a38-0000-1000-8000-00805f9b34fb',
}
class BLEManager {
bleManagerModule: any
bleManagerEmitter: any
scanning: boolean
dispatch: any
stopScanListener: any
peripheralDiscoverListener: any
characteristicUpdateListener: any
onDisconnectListener: any
connectTimeout: any
constructor() {
BleManager.start({ showAlert: false })
this.bleManagerModule = NativeModules.BleManager
this.bleManagerEmitter = new NativeEventEmitter(this.bleManagerModule)
this.scanning = false
}
startScan = (onPeripheralFound: (peripheral: Peripheral | null) => void) => {
if (!this.scanning) {
BleManager.scan([], 3, true)
.then(() => {
console.log('Scanning...')
this.scanning = true
this.peripheralDiscoverListener = this.bleManagerEmitter.addListener(
'BleManagerDiscoverPeripheral',
onPeripheralFound,
)
this.stopScanListener = this.bleManagerEmitter.addListener(
'BleManagerStopScan',
() => {
onPeripheralFound(END)
},
)
return
})
.catch(err => {
console.error(err)
})
} else {
console.log('already scanning')
}
return () => {
console.log('stopped scanning')
this.peripheralDiscoverListener.remove()
this.stopScanListener.remove()
}
}
getBondedDevices = (onGetBondedPeripherals: any) => {
BleManager.getBondedPeripherals().then(bondedPeripheralsArray => {
onGetBondedPeripherals(bondedPeripheralsArray)
// TODO: is the END message here necessary?
onGetBondedPeripherals(END)
return
})
return () => {}
}
connectToPeripheral = async (peripheralID: string) => {
try {
await new Promise(async (resolve, reject) => {
this.connectTimeout = setTimeout(reject, 3000)
console.log('connecting to ' + peripheralID)
try {
await BleManager.connect(peripheralID)
await BleManager.retrieveServices(peripheralID)
} catch (error) {
reject()
}
if (this.connectTimeout) {
clearTimeout(this.connectTimeout)
this.connectTimeout = null
this.onDisconnectListener = this.bleManagerEmitter.addListener(
'BleManagerDisconnectPeripheral',
this.onDisconnectPeripheral,
)
resolve()
}
})
} catch (err) {
clearTimeout(this.connectTimeout)
this.connectTimeout = null
console.error('Could not connect to device.')
throw new Error(err)
}
return
}
watchForCharacteristicsUpdates = async (
updateCharValue: (arg0: { payload: any }) => void,
peripheralID: string,
) => {
try {
await BleManager.startNotification(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.ERROR_UUID,
)
await BleManager.startNotification(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.VERSION_UUID,
)
await BleManager.startNotification(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.UPDATE_STATUS_UUID,
)
} catch (e) {
updateCharValue(new Error(e))
console.error(e)
}
console.log('watch for notifications')
this.characteristicUpdateListener = this.bleManagerEmitter.addListener(
'BleManagerDidUpdateValueForCharacteristic',
({ value, characteristic }) => {
// Convert bytes array to string
const data = bytesToString(value)
console.log(
`Received ${data} (${value}) for characteristic ${characteristic}`,
)
updateCharValue({
payload: {
characteristic: characteristic,
data: data,
},
})
},
)
}
disconnectFromPeripheral = async (peripheralID: string) => {
await BleManager.disconnect(peripheralID)
this.characteristicUpdateListener.remove()
}
onDisconnectPeripheral = (peripheralID: string) => {
console.log(peripheralID + ' disconnected')
this.onDisconnectListener.remove()
}
checkIfConnected = async (peripheralID: string) => {
return await BleManager.isPeripheralConnected(peripheralID, [])
}
triggerUpdateCheck = async (peripheralID: string) => {
return await BleManager.write(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.WIFI_STATUS_UUID,
[1],
)
}
runUpdate = async (peripheralID: string) => {
return await BleManager.write(
peripheralID,
UPDATE_SERVICE_UUID,
Characteristic.DO_UPDATE_UUID,
[1],
)
}
}
const bleManager = new BLEManager()
export default bleManager
I've researched this a bit and it seems that some people have the problem but I could not find an explanation or solution to it.
I'm even unsure where to start debugging. Any suggestions are welcome.
Details:
Device: [Pixel 6]
OS: [Android 12]
react-native-ble-manager version: ^8.4.1
react-native version: 0.67.4
Note: I've also asked this question on Github: https://github.com/innoveit/react-native-ble-manager/issues/887
The problem (as mentioned by Martijn) was the bug in Bluez which is fixed in 5.65. Simply upgrading and clearing the Bluetooth cache fixed it.
Firebase Function Code
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
const db = admin.firestore();
const gameRef = db.collection('Game');
function newRoom(uid) {
gameRef.add({
users: [
uid
],
playing: false,
moves: [],
win: ""
}).then(ref => {
return {
"game": ref.id
}
}).catch(err => {
console.log(err.message)
})
}
function joinRoom(uid, id, data) {
data.users.push(uid);
data.playing = true;
gameRef.doc(id).update(data)
.then(ref => {
return {
"game": id
}
}).catch(err => {
console.log(err.message);
})
;
}
exports.helloWorlds = functions.https.onCall((data, context) => {
const uid = context.auth.uid;
const query = gameRef.where('playing', '==', false).get()
.then(snapshot => {
if (snapshot.docs.length === 0) {
return newRoom(uid)
} else {
return joinRoom(uid, snapshot.docs[0].id, snapshot.docs[0].data())
}
}).catch(err => {
console.log(err.message)
});
});
Android Code
fun requestGame(text:String): Task<HashMap<*, *>> {
// Create the arguments to the callable function.
val data = hashMapOf("text" to text, "push" to true)
return mFunctions
.getHttpsCallable("helloWorlds")
.call(data)
.continueWith {
val result = it.result.data as HashMap<*, *>
result
}
function code works fine. When I make a request on the android device, it returns null. İt write the datas to the database smoothly. Another problem is that sometimes the function does not work when it is not running for a certain period of time. I think the problem is JavaScript, but I did not solve the problem
Right now you're not returning anything from helloWorlds itself, which means that Cloud Functions can't know when it's done. You'll want to return query at the end of helloWorlds:
exports.helloWorlds = functions.https.onCall((data, context) => {
const uid = context.auth.uid;
const query = gameRef.where('playing', '==', false).get()
.then(snapshot => {
if (snapshot.docs.length === 0) {
return newRoom(uid)
} else {
return joinRoom(uid, snapshot.docs[0].id, snapshot.docs[0].data())
}
}).catch(err => {
console.log(err.message)
});
return query;
});
return gameRef.where(...
exports.helloWorlds = functions.https.onCall((data, context) => {
const uid = context.auth.uid;
return gameRef.where('playing', '==', false).get()
.then(snapshot => {
if (snapshot.docs.length === 0) {
return newRoom(uid)
} else {
return joinRoom(uid, snapshot.docs[0].id, snapshot.docs[0].data())
}
}).catch(err => {
console.log(err.message)
});
});
I developed a mobile app to help sharing things. The user has to give infos about what he is sending and he can add a picture of the object. So i used the cordova file, camera and fileTransfert plugins. It worked fine on most of the devices i tested on, but i discovered that in some other phone, it doesn't. While doing some tests and research on one of those phones, i discovered that the upload() method of FileTransfert i use to send images to online server seems like not able to reach the folder where the image is stored. Here is a sample of my code. Would you please help me to confirm if i am rigth and how to make those phones to be able to post pictures on the platform?
public presentActionSheet(picture) {
if(this.translateService.currentLang=='fr'){
let actionSheet = this.actionSheetCtrl.create({
title: 'Quelle est la source?',
buttons: [
{
icon: 'images',
text: 'Mon téléphone',
handler: () => {
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY, picture);
}
},
{
icon: 'camera',
text: 'Ma Camera',
handler: () => {
this.takePicture(this.camera.PictureSourceType.CAMERA, picture);
}
},
{
text: 'Annuler',
role: 'cancel'
}
]
});
actionSheet.present();
}else{
let actionSheet = this.actionSheetCtrl.create({
title: 'What is the source?',
buttons: [
{
icon: 'images',
text: 'My Phone',
handler: () => {
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY, picture);
}
},
{
icon: 'camera',
text: 'My Camera',
handler: () => {
this.takePicture(this.camera.PictureSourceType.CAMERA, picture);
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
});
actionSheet.present();
}
};
presentToast(message_error) {
let toast = this.toastCtrl.create({
message: message_error,
cssClass: 'alert-box',
position: 'middle',
showCloseButton: true,
closeButtonText: "OK"
});
toast.present();
}
//Here is the function to take a picture
public takePicture(sourceType, picture) {
// Create options for the Camera Dialog
var options = {
quality: 100,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
// Get the data of an image
this.camera.getPicture(options).then((imagePath) => {
// Special handling for Android library
if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
this.filePath.resolveNativePath(imagePath)
.then(filePath => {
let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
this.copyFileToLocalDir(correctPath, currentName, this.createFileName(), picture);
});
} else {
console.log('In the else condition');
var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
this.copyFileToLocalDir(correctPath, currentName, this.createFileName(), picture);
}
}, (err) => {
if(this.translateService.currentLang=='fr'){
this.presentToast('Erreur, pas d\'image selectionnée.');
}else{
this.presentToast('Error, no image selected.');
}
});
}
// Create a new name for the image
private createFileName() {
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
return newFileName;
}
// Copy the image to a local folder
//cordova.file.dataDirectory
private copyFileToLocalDir(namePath, currentName, newFileName, picture) {
this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
if(picture == "imageOne"){
this.mainImage = newFileName;
}else if(picture == "imageTwo"){
this.secondImage = newFileName;
}else{
this.thirdImage = newFileName;
}
//this.lastImage = newFileName;
}, error => {
if(this.translateService.currentLang=='fr'){
this.presentToast('Erreur, le fichier n\'a pas pu etre sauvegardé.');
}else{
this.presentToast('Error, file could not be saved.');
}
console.log(error);
});
}
// Always get the accurate path to your apps folder
public pathForImage(img) {
if (img === null) {
return '';
} else {
return cordova.file.dataDirectory + img;
}
}
public uploadImage(picture) {
// Destination URL
var url = "http://donation.oneclub1.org/donation-new/web/api/upload/image?context=donations";
// File for Upload
var targetPath: any;
if(picture == "imageOne"){
targetPath = this.pathForImage(this.mainImage);
}else if(picture == "imageTwo"){
targetPath = this.pathForImage(this.secondImage);
}else{
targetPath = this.pathForImage(this.thirdImage);
}
// File name only
var filename: any;
if(picture == "imageOne"){
filename = this.mainImage;
}else if(picture == "imageTwo"){
filename = this.secondImage;
}else{
filename = this.thirdImage;
}
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': filename}
};
const fileTransfer: TransferObject = this.transfer.create();
// Use the FileTransfer to upload the image
return fileTransfer.upload(targetPath, url, options);/*.then(data => {
if(picture == "imageOne"){
this.mainImageLocal = parseInt(data.response);
}else if(picture == "imageTwo"){
this.secondImageLocal = parseInt(data.response);
}else{
this.thirdImageLocal = parseInt(data.response);
}
//this.presentToast('this is your image id'+this.mainImageLocal);
}, err => {
this.loading.dismissAll();
this.presentToast('Error while uploading file.');
})*/;
}
publish(){
if(this.mainImage!=null){
this.loading = this.loadingCtrl.create({
content: this.content2,
});
this.loading.present();
//var categoryId: number;
for(let parent of this.categories){
if(parent.name == this.asking_form_group.value.subcategory){
this.categoryId=parent.id;
console.log('Id found and it is:'+this.categoryId);
break;
};
};
//var userId: number;
if(localStorage.getItem('userId')){
this.userId= parseInt(localStorage.getItem('userId'));
console.log('got the user id in nmber:'+this.userId);
};
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
let options = new RequestOptions({ headers: headers });
this.uploadImage('imageOne').then(data => {
this.mainImageLocal = parseInt(data.response);
this.postParams = {
name: this.asking_form_group.value.name,
category: this.categoryId,
description: this.asking_form_group.value.description,
image: this.mainImageLocal,
user: this.userId
}
this.http.post(this.Api+"/donations/requests?api_key="+localStorage.getItem('userApiKey'), this.postParams, options).map(res => res.json())
.subscribe(data => {
this.loading.dismissAll();
if(this.translateService.currentLang=='fr'){
this.presentToast('Félicitations!!Votre demande a été postée sur la plateforme!')
}else{
this.presentToast ('Congratulations !! Your request has been posted on the platform!')
}
this.events.publish('ask:posted', 1);
this.navCtrl.setRoot(Dashboard);
}, error => {
console.log(error);
//this.asking_form_group.reset();
this.testor = error.response;
this.loading.dismissAll();
this.presentToast(this.error);
});
});
}else{
this.loading = this.loadingCtrl.create({
content: this.content2,
});
this.loading.present();
//var categoryId: number;
for(let parent of this.categories){
if(parent.name == this.asking_form_group.value.subcategory){
this.categoryId=parent.id;
console.log('Id found and it is:'+this.categoryId);
break;
};
};
if(localStorage.getItem('userId')){
this.userId= parseInt(localStorage.getItem('userId'));
console.log('got the user id in nmber:'+this.userId);
};
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
let options = new RequestOptions({ headers: headers });
this.postParams = {
name: this.asking_form_group.value.name,
category: this.categoryId,
description: this.asking_form_group.value.description,
image: this.mainImageLocal,
user: this.userId
}
this.http.post(this.Api+"/donations/requests?api_key="+localStorage.getItem('userApiKey'), this.postParams, options).map(res => res.json())
.subscribe(data => {
this.loading.dismissAll();
if(this.translateService.currentLang=='fr'){
this.presentToast('Félicitations!!Votre demande a été postée sur la plateforme!')
}else{
this.presentToast ('Congratulations !! Your request has been posted on the platform!')
}
this.events.publish('ask:posted', 1);
this.navCtrl.setRoot(Dashboard);
}, error => {
console.log(error);
//this.asking_form_group.reset();
this.testor = error.response;
this.loading.dismissAll();
this.presentToast(this.error);
});
};
}
Sorry i found what the issue was and i fogot to put it here. The problem was actually about filesize. Filetransfert default limit is 7.5Mo. Sending file greater than that would fail. In some phones, camera default configurations put the picture size to 8 or greater Mpx. So that why it could not work in those phones.
I am using Ionic Framework. I want to ask for help about how to insert more than 1000 rows at a time and while insertion showing a loading spinner to user so that there wont be any mess in database.
First, I have two services/factories.
Database :
.factory('DB', function ($ionicPopup, $cordovaSQLite, $q, $ionicPlatform, $cordovaNetwork,$ionicLoading) {
var self = this;
self.query = function (query, parameters) {
parameters = parameters || [];
var q = $q.defer();
$ionicPlatform.ready(function () {
$cordovaSQLite.execute(db, query, parameters)
.then(function (result) {
console.log(result);
q.resolve(result);
}, function (error) {
console.log(error+" .."+error.message);
alert('I found an error' + error.message);
q.reject(error);
});
});
return q.promise;
}
// Proces a result set
self.getAll = function (result) {
var output = [];
for (var i = 0; i < result.rows.length; i++) {
output.push(result.rows.item(i));
}
return output;
}
// Proces a single result
self.getById = function (result) {
var output = null;
output = angular.copy(result.rows.item(0));
return output;
}
return self;
})
Secondly, AsyncService for downloading data from multiple urls
.service('asyncService', function ($http, $q) {
return {
loadDataFromUrls: function (urls) {
alert("I am inside new Service ");
var deferred = $q.defer();
var urlCalls = [];
angular.forEach(urls, function (url) {
urlCalls.push($http.get(url.url));
});
// they may, in fact, all be done, but this
// executes the callbacks in then, once they are
// completely finished.
$q.all(urlCalls)
.then(
function (results) {
deferred.resolve(results)
},
function (errors) {
console.log(errors);
deferred.reject(errors);
},
function (updates) {
console.log(updates);
deferred.update(updates);
});
return deferred.promise;
}
};
})
And the method that firstly, should download the datas and then insert them into their belonged tables.
asyncService.loadDataFromUrls(urLs).then(function (result) {
DB.query("DELETE FROM INV");
// when i have to update the tables, i first delete them and then fill them back again.
$ionicLoading.show({
template : 'Processing into Database. Please Wait...',
timeout : '6000'
});
result.forEach(function (rows) {
console.log(rows.config.url);
var i = 0;
if (rows.config.url == 'http://11.444.222.55:55/mobil_op?op=get_inv') {
rows.data.forEach(function (entry) {
var parameters = [entry.code, entry.name,];
DB.query("INSERT INTO INV (CODE,NAME,......) VALUES(?,?........)",parameters);
})
}
})
}, function (err) {
alert("OOpsss ! : " + err.message);
console.log("error");
}, function (updates) {
alert("updates");
console.log("updates" + updates);
})
How should I work while inserting 4453 elements into array ?
db.executeSql("BEGIN TRANSACTION",{})
.then(( res )=> {
console.log(res);
// DO ALL INSERTION ON THE TABLES
// e.g
// AT LAST
db.executeSql("COMMIT",{})
.then(()=> console.log("COMMIT")
.catch(e => console.log(e));
}).catch(e => console.log(e));
// This process provided me much more faster way . The method above in the question dialog was inserting 4553 items in 3 minutes on Asus Zenphone 1. This method let me insert 10000 items less then 3 minutes.
I am trying to learn JSONStore and in process of that I am trying to execute a piece of code which will first check if a particular JSONStore is already there in the device or not and based on the result it will execute if-else statement. If it is not there, it will create one and add some data in it. In case the jsonStore is already present, code will replace the previously stored data with new data. But when I am trying to execute the code, my device shows the html contents for a while and then the screen gets blank. When I checked the logcat, I didn't get any of my console log statements which I have added in my code. Can anyone please help me in understanding this behavior and what could be done to achieve the requirement.
var JSONStoreCollections = {};
var collectionName = 'Person';
function wlCommonInit(){
require([ "layers/core-web-layer", "layers/mobile-ui-layer" ], dojoInit);
}
function dojoInit() {
require([ "dojo/ready", "dojo/parser", "dojox/mobile", "dojo/dom", "dijit/registry", "dojox/mobile/ScrollableView" ], function(ready) {
ready(function() {
if(!(WL.JSONStore.get(collectionName))){
console.log("i am in if codition");
var Data={
Name:'name',
Age:27
};
JSONStoreCollections[collectionName] = {};
JSONStoreCollections[collectionName].searchFields = {Name: 'string'};
WL.JSONStore.init(JSONStoreCollections)
.then(function () {
console.log("store created");
})
.fail(function (errorObject) {
console.log("store creation failed");
});
WL.JSONStore.get(collectionName).add(Data)
.then(function () {
console.log("data added");
})
.fail(function (errorObject) {
console.log("data addition failed");
});
var query = {Name: 'name'};
WL.JSONStore.get(collectionName)
.find(query)
.then(function (arrayResults) {
console.log(arrayResults);
WL.Logger.debug(arrayResults);
})
.fail(function (errorObject) {
console.log(errorObject);
WL.Logger.debug(errorObject);
});
}
else{
var Data1={
Name:'name1',
Age:30
};
WL.JSONStore.get(collectionName).replace(Data1)
.then(function () {
console.log("data replaced");
})
.fail(function (errorObject) {
console.log("data replacement failed");
});
var query = {Name: 'name1'};
WL.JSONStore.get(collectionName)
.find(query)
.then(function (arrayResults) {
console.log(arrayResults);
WL.Logger.debug(arrayResults);
})
.fail(function (errorObject) {
console.log(errorObject);
WL.Logger.debug(errorObject);
});
}
});
});
}
You need to initialize first, otherwise WL.JSONStore.get(collectionName) will always return undefined. If you never initialize JSONStore, you can not use it.
The replace API works with JSONStore documents (objects that have keys for _id and json).
You only need one .fail, the error object will tell you the source of the error (errorObject.src).
See the untested pseudocode below for what you want to do:
function wlCommonInit () {
var collectionName = 'Person';
var Data = {
Name: 'name',
Age: 27
};
var JSONStoreCollections = {};
JSONStoreCollections[collectionName] = {};
JSONStoreCollections[collectionName].searchFields = {Name: 'string'};
WL.JSONStore.init(JSONStoreCollections)
.then(function () {
WL.Logger.debug('Init done');
return WL.JSONStore.get(collectionName).findAll();
})
.then(function (res) {
WL.Logger.debug('Find All returned:', res);
if (res.length < 1) {
return WL.JSONStore.get(collectionName).add(Data);
} else {
res[0].json = {
Name:'name1',
Age:30
};
return WL.JSONStore.get(collectionName).replace(res[0]);
}
})
.then(function () {
WL.Logger.debug('Add or Replace done');
return WL.JSONStore.get(collectionName).find({Name: 'name'});
})
.then(function (res) {
WL.Logger.info('Final Find returned:', res);
})
.fail(function (err) {
WL.Logger.error(err);
});
}
Expected output the first time executed:
Init done
Find All returned: []
Add or Replace done
Final Find returned: [{"_id":1,"json":{"Name":"name","Age":27}}]
Expected output other than the first time executed:
Init done
Find All returned: [{"_id":1,"json":{"Name":"name","Age":27}}]
Add or Replace done
Final Find returned: [{"_id":1,"json":{"Name":"name1","Age":30}}]