Memory object in twilio - javascript

I need to maintain a common variable among 2 functions in Twilio. But it's not working as expected.
I tried to use variable inside memory like this:-
let memory = JSON.parse(event.Memory);
if(memory.twilio.counter === null) {
memory.twilio.counter = 0;
} else {
memory.twilio.counter = memory.twilio.counter + 1;
}
Is it not the correct way?
If not, is there any alternative?

Memory is a object presented by Twilio Autopilot, not Twilio Functions. If you want to share state between Functions (not using Autopilot), you need to place that state into external storage like Twilio Sync or Airtable, etc.
Sync is good is there are not a lot of read/write operations. See Tips for building with Sync API below.
Use Twilio Sync to create, read, update, delete persistent data
Tips for building with Sync API

Related

share firestore collection paths across admin and web

I'd like to make re-usable functions that get the Firestore Document/Collection reference across web and admin (node.js).
for example:
getUserDocumentReference(company: string, user: string) {
return firebase.collection("companies")
.doc(company)
.collection("users")
.doc(user);
}
This will reduce errors and coordinate changes across both environments.
Problem: Admin imports firestore from firebase-admin, and web imports from firebase.
I've tried making some class/function where I pass in my firestore reference, but it becomes a pain where I have to declare the return types:
const ref = (
getUserDocumentReference("a", "1") as
firebase.firestore.DocumentReference
)
.withConverter(converter)
Is there a smarter/cleaner way to do this without re-inventing the wheel (i.e. somehow passing an array or re-creating paths in a complex way)?
my current approach:
class FirestoreReferences {
constructor(firestore: firebase.firestore.Firestore
| admin.firestore.Firestore) {
this.firestore = firestore;
}
getUserDocumentReference(company: string, user: string): FirebaseFirestore.DocumentReference | firebase.firestore.DocumentReference {
return this.firestore.collection(...).doc(...);
}
}
Just found out about Typesaurus which provides generic types to share across web/admin!
The simplest answer: DO NOT use the .doc() or the .doc().ref. Use the .doc.ref.path - which is a string with the FULL PATH to the document. Save/share it as let refPath = whatever.doc().ref.path and re-build it as .doc(refPath) is either environment.
I DO NOT actually RECOMMEND this - it exposes your internal structure - but it isn't inherently insecure (your security rules better be taking care of that).
btw, I'm building an entire wrapper npm package (#leaddreamer/firebase-wrapper) for this specific purpose.
You should not do this. The Admin SDK is meant for server-side usage because it has full control over your entire project. If a user gets access to this, they have control over your app. Keep firebase and firebase-admin seperate.

Angular 6 - Share Instance of Object between different tabs and browsers

Recently I came across a slightly different problem. Here's the deal: I'm using an API that requires me to use the same instance across my whole application.
The problem is that my application runs in different tabs and different browsers at the same time and with that in mind my application keeps bootstrapping and creating new instances of the object that I need to use.
I've tried to create a service and inject in the APP module but at some point, a new instance will be generated.
Now I'm trying to use local storage to save the instance but when I retrieve my object I can't call the functions that belong to the object.
let storedObject = localStorage.getItem("storedObject");
if(storedObject == null) {
this.storeInstance();
} else {
let instancedObj = JSON.parse(storedObject);
instancedObj.somefunction(); // THIS DOESN'T WORK
}
storeInstance() {
const objThatNeedsToBeTheSame = new TestObject();
// key / value
localStorage.setItem("storedObject", JSON.stringify(objThatNeedsToBeTheSame));
}
I think this is a good use case for firebase real-time API database, and auth by a token.

Should I cache firebase refs?

I'm developing a web app backed with firebase realtime database.
The app's frontend is quite complex and there are several methods that write data to the db. I have several utils that look like this:
var utils = {
setSomething: function(id, item) {
var myRef = firebase.database().ref('my/path');
myRef.set(item).then(something);
}
}
The question here is: is it okay to create a new Ref inside the method (and thereby, creating a new ref with each call) or should I "cache" the ref somewhere else (just like we cache jquery objects).
I could do something like this first:
var cachedRefs = {
myRef: firebase.database().ref('my/path'),
yourRef: firebase.database().ref('your/path'),
herRef: firebase.database().ref('her/path')
}
And then the former method could be rewritten as:
var utils = {
setSomething: function(id, item) {
cachedRefs.myRef.set(item).then(something);
}
}
Is there any performance gain besides having less code repetition?
firebaser here
References just contain the location in the database. they are cheap.
Adding the first listener to a reference requires that we start synchronizing the data, so that is as expensive as the data you listen to. Adding extra listeners is then relatively cheap, since we de-duplicate the data synchronization across listeners.

AngularJS ui-router save previous state

I want to save the current state, I don't mean saving url and params, I want to save the entire view with scopes.. In fact, I want to implement a facebook like search system, but differently. I want to display the results on the entire page, so I'll replace the current main State, and when the search bar will be cleared, then we will restore the previous state. I don't want to rebuild the state to restore the state instantly (no server requests) + to avoid complicated operations (eg. infinite scroll data..). I've found ui'router extras (sticky state) plugin, but we need to define what state to save with states definitions..
I apologize for my bad english..
You can save the date in the local storage using angular local storage. It will save you a trip to the server for data.
This is an architectural decision. The answer to this question will not be short and can be very subjective and different people will have different ways to implementing it.
What I would suggest is that you leverage local storage and do all actions on data present in local storage.
The way you would do this is to first understand that all server requests need to be done through A service that return what's present in localstorage is network is offline.
So all AJAX calls will be done from the controller like this
var getMeRequest = AuthService.getMe();
getMeRequest.promise.then(function(response){
if(response.cached) {
// $update views if need be
} else {
//Some code
}
});
And in the AuthService file, you'd do it like this:
// In AuthService
this.getMe() = function () {
if(network.online) {
//Make AJAX call
// Update localstorage with whatever response
return {response: locastorageData, cached:false};
} else {
return {response: localstorageData, cached:true};
}
};
This will not only let you make all the ajax calls as if you were online, but also allow the controller to update the view based on whether the response is cached or not.

why knockout does not auto update by model changes?

in parse.com I opened up this account g2840904#trbvm.com/12345678.
I forked https://github.com/tachang/knockout_tasklist which synchronizes knockout to parse.com and when i start up the app i do see as the only item sometitle1 however if I change sometitle1 to sometitle2 in parse.com task class i don't see this being relfected automatically in the webapp. isn't that what knockout supposed to do when the variable title is defined as observabale?
this.title = ko.observable(data.title);
What should I do so it does reflect automatically changes in model? meaning changing for example sometitle1 to sometitle2 in parse.com would update the web page to reflect that change auotmatically and present sometitle2 instead of sometitle1?
It seems you misunderstand what KO is supposed to be doing. As a client-side library Knockout takes care to synchronize your UI with the underlying data model, which is provided by you via ko.observable variables, and not the database itself. There's a reason why apps are broken into 3 tiers - you've got the front-end which handles UI, the middle tier where all business logic resides and the back-end that serves as data storage. Knockout bridges the middle tier and the front-end, while you are asking for a direct bridge between the front and back-end.
That being said, you can provide this bridge yourself, but of course writing it from a scratch is somewhat painful exercise. The easiest possible way is to ask the db whether any new data has arrived every X seconds using setInterval:
var updateTasks = function () {
$.parse.get("task", {}, function(json) {
self.tasks.removeAll();
for( var i = 0; i < json.results.length ; i++ ) {
var task = json.results[i];
self.tasks.push(new Task({ title: task.title, objectId: task.objectId }));
}
})
}
setInterval(updateTasks, 5000);

Categories