When I run the code, it shows "User was registered successfully", but followed with "Cannot read property 'email' of undefined".
I try to fix the error, but failed. I think it may be some error in userRecord, but I checked many times and can't find what's the problem.
Here is my code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var admin = require("firebase-admin");
var userAccountRequests = (io) =>{
io.on('connection',(socket)=>{
console.log(`Client ${socket.id} is connected`);
detectDisconnection(socket,io);
registerUser(socket,io);
});
};
I think there may be some error here. It can show the "successfully" message, but I think I have defined email.
function registerUser(socket,io){
socket.on('userData',(data)=>{
admin.auth().createUser({
email:data.email,
displayname:data.userName,
password:data.password
})
.then((userRecord)=>{
console.log('User was registered successfully');
var db = admin.database();
var ref = db.ref('users');
var userRef = ref.child(encodeEmail(data.email));
var data = {
data:admin.database.ServerValue.TIMESTAMP
};
userRef.ser({
email:data.email,
userName:data.userName,
dataJoined:date,
hasLoggedIn:false
});
//send message to Client
Object.keys(io.sockets.sockets).forEach((id)=>{
if(id == socket.id){
var message = {
text:'Success'
}
io.to(id).emit('message',{message});
}
});
}).catch((error)=>{
Object.keys(io.sockets.sockets).forEach((id)=>{
console.log(error.message);
if(id == socket.id){
var message = {
text:error.message
}
io.to(id).emit('message',{message});
}
});
});
});
}
function detectDisconnection(socket,io){
socket.on('disconnect',()=>{
console.log('Client has disconnected');
});
}
function encodeEmail(email) {
return email.replace('.',',');
}
module.exports = {
userAccountRequests
}
The 'data' object is only active within the function in 'on', this code:
socket.on('userData',(data)=>{
admin.auth().createUser({
email:data.email,
displayname:data.userName,
password:data.password
})
At the end of this function, 'data' is no longer defined. The 'then' that follows is using 'userRecord' instead.
You should change your 'data' references to 'userRecord', like this:
function registerUser(socket,io){
socket.on('userData',(data)=>{
admin.auth().createUser({
email:data.email,
displayname:data.userName,
password:data.password
})
.then((userRecord)=>{
console.log('User was registered successfully');
var db = admin.database();
var ref = db.ref('users');
var userRef = ref.child(encodeEmail(userRecord.email));
// not sure what this is about
var data = {
data:admin.database.ServerValue.TIMESTAMP
};
userRef.ser({
email:userRecord.email,
userName:userRecord.userName,
dataJoined:date,
hasLoggedIn:false
});
//send message to Client
Object.keys(io.sockets.sockets).forEach((id)=>{
if(id == socket.id){
var message = {
text:'Success'
}
io.to(id).emit('message',{message});
}
});
}).catch((error)=>{
Related
Am trying to add Stripe to my android app with Firebase. I set the publishable key in gradle.properties and builtype in gradle.build then call in application as BuildConfig.PublishableKey
Every time I try to add card a dialog pops up with this warning...
unexpected char 0x0a at 9 header value: bearer pk_test_xxxxkeyxxxx
Any ideas? Am using prebuilt UI from stripe too (presentPaymentMethodSelection() ) following their Firebase mobile payments android
var RC_SIGN_IN = 1
class MainActivityStripe : AppCompatActivity() {
private var currentUser: FirebaseUser? = null
private lateinit var paymentSession: PaymentSession
private lateinit var selectedPaymentMethod: PaymentMethod
private val stripe: Stripe by lazy { Stripe(applicationContext,
PaymentConfiguration.getInstance(applicationContext).publishableKey) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_stripe)
currentUser = FirebaseAuth.getInstance().currentUser
payButton.isEnabled = false
loginButton.setOnClickListener {
// login to firebase
val providers = arrayListOf(
AuthUI.IdpConfig.EmailBuilder().build())
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.build(),
RC_SIGN_IN
)
}
payButton.setOnClickListener {
confirmPayment(selectedPaymentMethod.id!!)
}
paymentmethod.setOnClickListener {
Toast.makeText(applicationContext, PaymentConfiguration.getInstance(applicationContext).publishableKey, Toast.LENGTH_LONG).show()
// Create the customer session and kick start the payment flow
paymentSession.presentPaymentMethodSelection()
}
showUI()
}
private fun confirmPayment(paymentMethodId: String) {
val paymentCollection = Firebase.firestore
.collection("stripe_customers").document(currentUser?.uid?:"")
.collection("payments")
// Add a new document with a generated ID
paymentCollection.add(hashMapOf(
"amount" to 8800,
"currency" to "cad"
))
.addOnSuccessListener { documentReference ->
Log.d("paymentsss", "DocumentSnapshot added with ID: ${documentReference.id}")
documentReference.addSnapshotListener { snapshot, e ->
if (e != null) {
Log.w("paymentsss", "Listen failed.", e)
return#addSnapshotListener
}
if (snapshot != null && snapshot.exists()) {
Log.d("paymentsss", "Current data: ${snapshot.data}")
val clientSecret = snapshot.data?.get("client_secret")
Log.d("paymentsss", "Create paymentIntent returns $clientSecret")
clientSecret?.let {
stripe.confirmPayment(this, ConfirmPaymentIntentParams.createWithPaymentMethodId(
paymentMethodId,
(it as String)
))
checkoutSummary.text = "Thank you for your payment"
Toast.makeText(applicationContext, "Payment Done!!", Toast.LENGTH_LONG).show()
}
} else {
Log.e("paymentsss", "Current payment intent : null")
payButton.isEnabled = true
}
}
}
.addOnFailureListener { e ->
Log.w("paymentsss", "Error adding document", e)
payButton.isEnabled = true
}
}
private fun showUI() {
currentUser?.let {
loginButton.visibility = View.INVISIBLE
greeting.visibility = View.VISIBLE
checkoutSummary.visibility = View.VISIBLE
payButton.visibility = View.VISIBLE
paymentmethod.visibility = View.VISIBLE
greeting.text = "Hello ${it.displayName}"
setupPaymentSession()
}?: run {
// User does not login
loginButton.visibility = View.VISIBLE
greeting.visibility = View.INVISIBLE
checkoutSummary.visibility = View.INVISIBLE
paymentmethod.visibility = View.INVISIBLE
payButton.visibility = View.INVISIBLE
payButton.isEnabled = false
}
}
private fun setupPaymentSession () {
// Setup Customer Session
CustomerSession.initCustomerSession(this, FirebaseEphemeralKeyProvider())
// Setup a payment session
paymentSession = PaymentSession(this, PaymentSessionConfig.Builder()
.setShippingInfoRequired(false)
.setShippingMethodsRequired(false)
.setBillingAddressFields(BillingAddressFields.None)
.setShouldShowGooglePay(true)
.build())
paymentSession.init(
object: PaymentSession.PaymentSessionListener {
override fun onPaymentSessionDataChanged(data: PaymentSessionData) {
Log.d("PaymentSession1", "11PaymentSession has changed: $data")
Log.d("PaymentSession11", "1111 ${data.isPaymentReadyToCharge} <> ${data.paymentMethod}")
if (data.isPaymentReadyToCharge) {
Log.d("PaymentSession2", "222Ready to charge");
payButton.isEnabled = true
data.paymentMethod?.let {
Log.d("PaymentSession3", "333PaymentMethod $it selected")
paymentmethod.text = "${it.card?.brand} card ends with ${it.card?.last4}"
selectedPaymentMethod = it
}
}
}
override fun onCommunicatingStateChanged(isCommunicating: Boolean) {
Log.d("PaymentSession4", "444isCommunicating $isCommunicating")
}
override fun onError(errorCode: Int, errorMessage: String) {
Log.e("PaymentSession5", "555onError: $errorCode, $errorMessage")
}
}
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val response = IdpResponse.fromResultIntent(data)
if (resultCode == Activity.RESULT_OK) {
currentUser = FirebaseAuth.getInstance().currentUser
Log.d("Login", "User ${currentUser?.displayName} has signed in.")
Toast.makeText(applicationContext, "Welcome ${currentUser?.displayName}", Toast.LENGTH_SHORT).show()
showUI()
} else {
Log.d("Login", "Signing in failed!")
Toast.makeText(applicationContext, response?.error?.message?:"Sign in failed", Toast.LENGTH_LONG).show()
}
} else {
paymentSession.handlePaymentData(requestCode, resultCode, data ?: Intent())
}
}
}**
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const { Logging } = require('#google-cloud/logging');
const logging = new Logging({
projectId: process.env.GCLOUD_PROJECT,
});
admin.initializeApp();
const stripe = require('stripe')(functions.config().stripe.secret, {
apiVersion: '2020-03-02',
});
exports.createEphemeralKey = functions.https.onCall(async (data, context) => {
// Checking that the user is authenticated.
if (!context.auth) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called while authenticated!'
);
}
const uid = context.auth.uid;
try {
if (!uid) throw new Error('Not authenticated!');
// Get stripe customer id
const customer = (
await admin.firestore().collection('stripe_customers').doc(uid).get()
).data().customer_id;
const key = await stripe.ephemeralKeys.create(
{ customer: customer },
{ apiVersion: data.api_version }
);
return key;
} catch (error) {
throw new functions.https.HttpsError('internal', error.message);
}
});
exports.createStripeCustomer = functions.auth.user().onCreate(async (user) => {
const customer = await stripe.customers.create({
email: user.email,
metadata: { firebaseUID: user.uid },
});
await admin.firestore().collection('stripe_customers').doc(user.uid).set({
customer_id: customer.id,
});
return;
});
exports.createStripePayment = functions.firestore
.document('stripe_customers/{userId}/payments/{pushId}')
.onCreate(async (snap, context) => {
const { amount, currency } = snap.data();
try {
// Look up the Stripe customer id.
const customer = (await snap.ref.parent.parent.get()).data().customer_id;
// Create a charge using the pushId as the idempotency key
// to protect against double charges.
const idempotencyKey = context.params.pushId;
const payment = await stripe.paymentIntents.create(
{
amount,
currency,
customer,
},
{ idempotencyKey }
);
// If the result is successful, write it back to the database.
await snap.ref.set(payment);
} catch (error) {
// We want to capture errors and render them in a user-friendly way, while
// still logging an exception with StackDriver
console.log(error);
await snap.ref.set({ error: userFacingMessage(error) }, { merge: true });
await reportError(error, { user: context.params.userId });
}
});
const updatePaymentRecord = async (id) => {
// Retrieve the payment object to make sure we have an up to date status.
const payment = await stripe.paymentIntents.retrieve(id);
const customerId = payment.customer;
// Get customer's doc in Firestore.
const customersSnap = await admin
.firestore()
.collection('stripe_customers')
.where('customer_id', '==', customerId)
.get();
if (customersSnap.size !== 1) throw new Error('User not found!');
// Update record in Firestore
const paymentsSnap = await customersSnap.docs[0].ref
.collection('payments')
.where('id', '==', payment.id)
.get();
if (paymentsSnap.size !== 1) throw new Error('Payment not found!');
await paymentsSnap.docs[0].ref.set(payment);
};
exports.cleanupUser = functions.auth.user().onDelete(async (user) => {
const dbRef = admin.firestore().collection('stripe_customers');
const customer = (await dbRef.doc(user.uid).get()).data();
await stripe.customers.del(customer.customer_id);
// Delete the customers payments & payment methods in firestore.
const snapshot = await dbRef
.doc(user.uid)
.collection('payment_methods')
.get();
snapshot.forEach((snap) => snap.ref.delete());
await dbRef.doc(user.uid).delete();
return;
});
exports.handleWebhookEvents = functions.https.onRequest(async (req, resp) => {
const relevantEvents = new Set([
'payment_intent.succeeded',
'payment_intent.processing',
'payment_intent.payment_failed',
'payment_intent.canceled',
]);
let event;
try {
event = stripe.webhooks.constructEvent(
req.rawBody,
req.headers['stripe-signature'],
functions.config().stripe.webhooksecret
);
} catch (error) {
console.error('❗️ Webhook Error: Invalid Secret');
resp.status(401).send('Webhook Error: Invalid Secret');
return;
}
if (relevantEvents.has(event.type)) {
try {
switch (event.type) {
case 'payment_intent.succeeded':
case 'payment_intent.processing':
case 'payment_intent.payment_failed':
case 'payment_intent.canceled':{
const id = event.data.object.id;
await updatePaymentRecord(id);
break;
}
default:
throw new Error('Unhandled relevant event!');
}
} catch (error) {
console.error(
`❗️ Webhook error for [${event.data.object.id}]`,
error.message
);
resp.status(400).send('Webhook handler failed. View Function logs.');
return;
}
}
// Return a response to Stripe to acknowledge receipt of the event.
resp.json({ received: true });
});
function reportError(err, context = {}) {
// This is the name of the StackDriver log stream that will receive the log
// entry. This name can be any valid log stream name, but must contain "err"
// in order for the error to be picked up by StackDriver Error Reporting.
const logName = 'errors';
const log = logging.log(logName);
// https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/MonitoredResource
const metadata = {
resource: {
type: 'cloud_function',
labels: { function_name: process.env.FUNCTION_NAME },
},
};
// https://cloud.google.com/error-reporting/reference/rest/v1beta1/ErrorEvent
const errorEvent = {
message: err.stack,
serviceContext: {
service: process.env.FUNCTION_NAME,
resourceType: 'cloud_function',
},
context: context,
};
// Write the error log entry
return new Promise((resolve, reject) => {
log.write(log.entry(metadata, errorEvent), (error) => {
if (error) {
return reject(error);
}
return resolve();
});
});
}
// [END reporterror]
/**
* Sanitize the error message for the user.
*/
function userFacingMessage(error) {
return error.type
? error.message
: 'An error occurred, developers have been alerted';
}
buildTypes.each {
it.buildConfigField 'String', 'PublishableKey', stripePublishableKey
}
import android.util.Log
import com.google.firebase.functions.FirebaseFunctionsException
import com.google.firebase.functions.ktx.functions
import com.google.firebase.ktx.Firebase
import com.stripe.android.EphemeralKeyProvider
import com.stripe.android.EphemeralKeyUpdateListener
class FirebaseEphemeralKeyProvider: EphemeralKeyProvider {
override fun createEphemeralKey(
apiVersion: String,
keyUpdateListener: EphemeralKeyUpdateListener
) {
val data = hashMapOf(
"api_version" to apiVersion
)
// User firebase to call the functions
Firebase.functions
.getHttpsCallable("createEphemeralKey")
.call(data)
.continueWith { task ->
if (!task.isSuccessful) {
val e = task.exception
if (e is FirebaseFunctionsException) {
val code = e.code
val message = e.message
Log.e("EphemeralKey", "Ephemeral key provider returns error: $e $code $message")
}
}
val key = task.result?.data.toString()
Log.d("EphemeralKey", "Ephemeral key provider returns $key")
keyUpdateListener.onKeyUpdate(key)
}
}
}
import android.app.Application
import com.stripe.android.PaymentConfiguration
class MyApp : Application(){
override fun onCreate() {
super.onCreate()
PaymentConfiguration.init(applicationContext, BuildConfig.PublishableKey)
}
}```
>2020-09-07 09:23:29.753 15967-15967/com.asgd.indigenoussource D/PaymentSession4: 444isCommunicating true
>2020-09-07 09:23:29.754 15967-15967/com.asgd.indigenoussource D/PaymentSession1: 11PaymentSession has changed: PaymentSessionData(isShippingInfoRequired=false, isShippingMethodRequired=false, cartTotal=0, shippingTotal=0, shippingInformation=null, shippingMethod=null, paymentMethod=null, useGooglePay=false)
>2020-09-07 09:23:29.754 15967-15967/com.asgd.indigenoussource D/PaymentSession11: 1111 false <> null
>2020-09-07 09:23:31.636 15967-15967/com.asgd.indigenoussource D/PaymentSession4: 444isCommunicating false
After getting some help from someone with stripe was able to get it working. My publishable key some how got changed within gradle and that key gets linked with device. I had to make new emulated device and reset everything
i'm new to firebase cloud function, My situation is Whenever a new article is published in the database, I need to show the notification to my app user.
my code
var functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/article/{articleId}')
.onWrite((event: { data: any; }) => {
var eventSnapshot = event.data;
var str1 = "Author is ";
var str = str1.concat(eventSnapshot.child("author").val());
console.log(str);
var topic = "android";
var payload = {
data: {
title: eventSnapshot.child("title").val(),
author: eventSnapshot.child("author").val()
}
};
return admin.messaging().sendToTopic(topic, payload)
.then(function (response: any) {
console.log("Successfully sent message:", response);
})
.catch(function (error: any) {
console.log("Error sending message:", error);
});
});
Here is my database structure in Firebase.
And the full Stacktrace from logcat is here.
TypeError: Cannot read property 'child' of undefined
at exports.sendNotification.functions.database.ref.onWrite (/srv/lib/index.js:17:41)
at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
at /worker/worker.js:825:24
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
sendNotification
Function execution took 286 ms, finished with status: 'error'
Note that onWrite() handler accepts a Change object which has before & after properties, but not data. I guess it's the cause of the problem, see onWrite() documentation. If you want to get the updated data use event.after.child('author') instead of event.data.child('author').
exports.sendNotification = functions.database.ref('/article/{articleId}').onWrite(change => {
// Exit when the data is deleted.
if (!change.after.exists()) {
return null;
}
const author = change.after.child('author').val();
...
});
I am sending push notification from iOS and Android both by calling a cloud function, and in each device I am getting 5 times a single push notification. I am using parse database hosted on back4app.
Cloud code is given below:
Parse.Cloud.define("push", function (request, response) {
var query = new Parse.Query(Parse.Installation);
var userID = request.params.user;
var message = request.params.message;
var notificationType = request.params.notificationType;
var user = new Parse.User();
user.id = userID;
query.equalTo('user', user);
query.equalTo("allowPush", true);
Parse.Push.send({
where: query,
data: {
alert: message,
sound: 'default',
"type": notificationType
}
}, { useMasterKey: true });
});
Try to call reponse.success and response.error functions in the end of your cloud code function. Since your client code is not receiving the feedback if the call worked or not it is probably attempting to send again.
Parse.Cloud.define("push", function (request, response) {
var query = new Parse.Query(Parse.Installation);
var userID = request.params.user;
var message = request.params.message;
var notificationType = request.params.notificationType;
var user = new Parse.User();
user.id = userID;
query.equalTo('user', user);
query.equalTo("allowPush", true);
Parse.Push.send({
where: query,
data: {
alert: message,
sound: 'default',
"type": notificationType
}
},
{
success: function () { response.success(); },
error: function(err) { response.error(err); },
useMasterKey: true
});
});
I tried to insert an image to db and get back as json data for mobile developing. I can successfully insert the path and retrieve the path as json but when i my friend tried to access the url it shows no such file or found.
This is the code
var express=require("express");
var app=express();
var fs = require("fs");
var sql=require('mysql');
var http = require("http");
var server = http.createServer();
var bodyParser = require('body-parser');
// app.use(bodyParser());
var multer = require('multer');
// var upload=multer({dest:'tmp/'});
// app.use(express.static('public'));
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'C:/Users/Ramachandran/Desktop/File/tmp/upload')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })
app.use(bodyParser.urlencoded({extended: true}));
var con=sql.createConnection({
host:"localhost",
user:"root",
password:'',
database:'test'
});
app.get('/',function (req,res){
con.connect(function(err){
if(err){
console.log(err);
return;
}
console.log("connection established");
res.send("connection established");
});
})
app.get('/index',function(req,res){
res.sendFile('index.html',{'root': __dirname });
})
app.post('/insert', upload.single("myfile"), function (req,res){
var tes = __dirname + "/" + req.file.originalname;
fs.writeFile(tes, data, function (err) {
if (err) {
console.log(err);
} else {
var response = {
message: 'File uploaded successfully',
filename: req.file.originalname
};
}
console.log(response);
});
var data = {
uid:req.body.RollNo,
pat:req.file.path
};
con.query("insert into src set ?",data, function (err,rows){
if(err) throw err;
res.send("Value has bee inserted");
})
})
app.get('/test',function(req,res){
con.query('select * from src',function (err,rows){
if(err) throw err;
console.log("data receive from db");
console.log(rows);
res.send(rows);
})
})
app.listen(8888);
This my Json data
[{"uid":78965,"pat":"C:\\Users\\Vasanth\\Desktop\\File\\tmp\\upload\\myfile-1467012273947"},{"uid":987,"pat":"C:\\Users\\Vasanth\\Desktop\\File\\tmp\\upload\\myfile-1467012387236"}]
This will not work as you are returning a local path. The file is present on your machine, but when your friend tries to download it, he is trying to find it in C:\\Users\\Vasanth\\Desktop\\File\\tmp\\upload\\myfile-1467012273947 on his machine. You need to save the file on a folder, that is exposed by the server and provide the file from there, i.e. - http://localhost:8888/files/myfile-1467012273947 The easiest way to achieve this is using the express.static middleware: http://expressjs.com/en/starter/static-files.html
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}}]