I'm not really understand what's the temporary storage means.
recently I have an issue:
We can deliver a variable to the function by TwiML, but it's have size/length limit. So I have to save this variable to global, so I can get this variable in anywhere(function) I want. But I'm worry if the variable will be changed by some others, because our function in twilio is serverless. In fact, global variable is not safe. Anyone can solve this?
I want to ask may I use temporary storage to resolve this?
Thanks.
Twilio developer evangelist here.
A coworker, a solutions engineer based in the UK, wrote this great blog post on using temporary storage in a Twilio Function.
The code in your Twilio Function would look something like
/**
*
* This Function shows you how to reach and utilise the temporary storage under the Function layer, mainly for single-invocation jobs
* For example, on each invocation we can create a file based on user data and use it accordingly
*
* IMPORTANT: Do NOT treat this storage as long term storage or for personal data that need to persist.
* The contents get deleted whenever the associated container is brought down, so this function is useful for one time actions
*
*/
var fs = require('fs');
var path = require('path');
var tmp_dir = require('os').tmpdir();
exports.handler = function(context, event, callback) {
/*We create a text file and we put some data in it*/
fs.writeFile(path.join(tmp_dir, 'test_file.txt'), 'Contents of created file in OS temp directory', function(err) {
if (err) callback(err);
/*We read the contents of the temporary directory to check that the file was created. For multiple files you can create a loop*/
fs.readdir(tmp_dir, function(err, files) {
if (err) callback(err);
callback(null, "File created in temporary directory: " + files.join(", "));
});
});
};
If you want to use temporary storage from the Twilio CLI, you can do so by running this command inside a project that you created with the Serverless Toolkit:
twilio serverless:new example --template=temp-storage
This Function template is also here on the Twilio Labs GitHub page.
Let me know if this helps at all!
enter image description here
The code looks like this:
In widget api_get_account_status, I save correlationId to function storage-CallSid;
In function storage-CallSid, I save correlationId to the "temporary storage";
In widget split_check_call_type, I invoke another function get-storage-CallSid;
In function get-storage-CallSid, may I get correlationId from "temporary storage"?
Related
I am using the realtime database and I am using transactions to ensure the integrity of my data set. In my example below I am updating currentTime on every update.
export const updateTime = functions.database.ref("/users/{userId}/projects/{projectId}")
.onUpdate((snapshot) => {
const beforeData = snapshot.before.val();
const afterData = snapshot.after.val();
if (beforeData.currentTime !== afterData.currentTime) {
return Promise.resolve();
} else {
return snapshot.after.ref.update( {currentTime: new Date().getTime()})
.catch((err) =>{
console.error(err);
});
}
});
It seems the cloud function is not part of the transaction, but triggers multiple updates in my clients, which I try to avoid.
For example, I watched this starter tutorial which replaces :pizza: with a pizza emoji. In my client I would see :pizza: for one frame before it gets replaced with the emoji. I know, the pizza tutorial is just an example, but I am running into a similar issue. Any advice is highly appreciated!
Cloud Functions don't run as part of the database transaction indeed. They run after the database has been updated, and receive "before" and "after" snapshots of the affected data.
If you want a Cloud Function to serve as an approval process, the idiomatic approach is to have the clients write to a different location (typically called a pending queue) that the function listens to. The function then performs whatever operation it wants, and writes the result to the final location.
I'd like to write an electron app, which is based on a number of windows.
Using this app, I'd like to be able to log in into a web-app using different roles in different windows.
Therefore, I need a feature to store cookies in different windows of the app at different locations. HTML, JS code and cookies data of window A should not see that of windows B.
Alternatively, I could image to somehow trap set-cookie requests and keep them in memory, thus not using app global cookie storage on HD.
Could someone provide code for this feature?
I'm aware of this post, which explains how to app.setPath() of userData. Unfortunately userData is app-global, not e.g. window local.
If I would be now able to trap each cookie-set operation of each BrowserWindow, I would be able to use app.setPath() and switch the cookie storage based on the window, the trap was fired.
I did find a solution:
First create a partition. Let name it SomeNameForMySession :
const partition = 'persist:SomeNameForMySession'
Then pass the partition to a BrowserWindow like so at creation time:
var ctrlWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
partition: partition
}
})
If another BrowserWindow gets another partition with another name, the windows have fully separated cookies.
If another BrowserWindow gets the same partition, the windows share cookie storage.
Using this, you may for example trace, what cookie events happen in session of the named partition:
// First find the correct session based on the partitions name
const ses2 = session.fromPartition( partition2 )
// Then, add a listener
ses2.cookies.addListener( 'changed', function ( event, cookie, cause, removed ) {
console.log('COOKIE: ' + cookie.name + ' :: ' + cookie.value )
})
In https://github.com/holochain/holochat-rust, how are the files ui/holoclient.js and ui/holoclient.map obtained ?
Also, is there any official documentation about that that I missed and is this still the way to get a UI to talk to the holochain container ?
ui/holoclient.js is a tiny library that makes it much easier to talk to a running Holochain app instance. The current way of connecting your GUI to an instance is a JSON-RPC-like process via a local WebSocket connection. It's intended as a nice wrapper to make zome function calls feel like local, in-browser function calls. Documentation is currently very light, but it shouldn't take much to figure out how it's supposed to work using the example. In a nutshell:
const url = 'ws://localhost:3000/'
window.holoclient.connect(url).then(({call, close}) => {
document.getElementById('form').addEventListener('submit', e => {
e.preventDefault()
// First, get a list of locally running Holochain instances...
call('info/instances')().then(info => {
// Now that we have instance info, we can make zome calls into any of them
// by referring to them by DNA hash (and agent ID) as specified in our
// container config.
// Search for the instance we're looking for, given known DNA and agent
// hashes.
const matchingInstances = Object.entries(info)
.find(([id, value]) => value.dna === 'blog_dna_hash' && value.agent === 'my_agent_hash')
const instance = getInstance(info, 'the_dna_hash', 'the_agent_hash')
const content = document.querySelector('#message').value
// Make another zome call now
call(instance, 'blog', 'main', 'create_post')({
content: content
})
})
})
})
It's written in TypeScript, which would mean that ui/holoclient.map is a 'source map', a file which maps line numbers in the compiled JavaScript file to line numbers in the original TypeScript source. Both Chrome and Firefox look for and use those source maps when you're debugging your JS.
With the new Firebase API you can upload files into cloud storage from client code. The examples assume the file name is known or static during upload:
// Create a root reference
var storageRef = firebase.storage().ref();
// Create a reference to 'mountains.jpg'
var mountainsRef = storageRef.child('mountains.jpg');
// Create a reference to 'images/mountains.jpg'
var mountainImagesRef = storageRef.child('images/mountains.jpg');
or
// File or Blob, assume the file is called rivers.jpg
var file = ...
// Upload the file to the path 'images/rivers.jpg'
// We can use the 'name' property on the File API to get our file name
var uploadTask = storageRef.child('images/' + file.name).put(file);
With users uploading their own files, name conflicts are going to be an issue. How can you have Firebase create a filename instead of defining it yourself? Is there something like the push() feature in the database for creating unique storage references?
Firebase Storage Product Manager here:
TL;DR: Use a UUID generator (in Android (UUID) and iOS (NSUUID) they are built in, in JS you can use something like this: Create GUID / UUID in JavaScript?), then append the file extension if you want to preserve it (split the file.name on '.' and get the last segment)
We didn't know which version of unique files developers would want (see below), since there are many, many use cases for this, so we decided to leave the choice up to developers.
images/uuid/image.png // option 1: clean name, under a UUID "folder"
image/uuid.png // option 2: unique name, same extension
images/uuid // option 3: no extension
It seems to me like this would be a reasonable thing to explain in our documentation though, so I'll file a bug internally to document it :)
This is the solution for people using dart
Generate the current date and time stamp using:-
var time = DateTime.now().millisecondsSinceEpoch.toString();
Now upload the file to the firebase storage using:-
await FirebaseStorage.instance.ref('images/$time.png').putFile(yourfile);
You can even get the downloadable url using:-
var url = await FirebaseStorage.instance.ref('images/$time.png').getDownloadURL();
First install uuid - npm i uuid
Then define the file reference like this
import { v4 as uuidv4 } from "uuid";
const fileRef = storageRef.child(
`${uuidv4()}-${Put your file or image name here}`
);
After that, upload with the file with the fileRef
fileRef.put(Your file)
In Android (Kotlin) I solved by combining the user UID with the milliseconds since 1970:
val ref = storage.reference.child("images/${auth.currentUser!!.uid}-${System.currentTimeMillis()}")
code below is combination of file structure in answer from #Mike McDonald , current date time stamp in answer from # Aman Kumar Singh , user uid in answer from #Damien : i think it provides unique id, while making the firebase storage screen more readable.
Reference ref = firebaseStorage
.ref()
.child('videos')
.child(authController.user.uid)
.child(DateTime.now().millisecondsSinceEpoch.toString());
I try to get the service metadata of a sapui5 v2 odata model.
Code:
var oModel = new sap.ui.model.odata.v2.ODataModel(someServiceURL);
var oMetadata = oModel.getServiceMetadata();
This should work according to this page:
https://openui5beta.hana.ondemand.com/docs/guide/6c47b2b39db9404582994070ec3d57a2.html
Anyhow I got "undefined" for oMetadata.
If I change code to:
var oModel = new sap.ui.model.odata.v2.ODataModel({
loadMetadataAsync : false,
serviceUrl : someServiceURL
});
Still oMetadata === undefined
According to SDK documentation metadata should be loaded in sync:
Return the metadata object. Please note that when using the model with
bLoadMetadataAsync = true then this function might return undefined
because the metadata has not been loaded yet. In this case attach to
the metadataLoaded event to get notified when the metadata is
available and then call this function.
What is wrong with my code?
I am using (1.28.11):
<script src="https://sapui5.netweaver.ondemand.com/resources/sap-ui-core.js" ...
I started debugging the UI5 code and detected following line:
this.bLoadMetadataAsync = true;
I started debugging of SAPUI5 code and detected following line (seems to be called each time):
this.bLoadMetadataAsync = true;
Is it a bug? Or is something wrong with my code?
Solution:
The following worked for me in an actual application environment. I guess it not being fired in my fiddle was due to no actual data request being made:
var oModel = new sap.ui.model.odata.v2.ODataModel(<ServiceURL>);
oModel.attachMetadataLoaded(null, function(){
var oMetadata = oModel.getServiceMetadata();
console.log(oMetadata);
},null);
Lead up to the solution:
Ok so I started playing around with this a bit and found the following:
.getServiceMetadata() worked fine with sap.ui.model.odata.ODataModel.
with the sap.ui.model.odata.v2.ODataModel the request for the metadata was sent through the network but somehow .getServiceMetadata() returned undefined.
I tried to sap.ui.model.odata.v2.ODataModel.attachMetadataLoaded() but the event was never fired. (This only applied in the jsbin I used)
I will edit this with any further findings I make. If you have anything that should be included in my findings/testing just tell me.
Edit:
The bLoadMetadataAsync is a parameter you can set on the sap.ui.model.odata.ODataModel. The parameter is not in the API for sap.ui.model.odata.v2.ODataModel anymore. I assume that the async loading has been choosen as default.
Edit:
#user3783327 Reported a bug here: https://github.com/SAP/openui5/issues/564
As sirion already mentioned, the ODataModel has now an API named metadataLoaded which returns a promise accordingly. In the resolve function, we can definitely get the service metadata via getServiceMetadata().
myODataModel.metadataLoaded()
.then(() =>/* Do something with */myODataModel.getServiceMetadata());
Alternatively, we can also make use of ODataMetaModel which can be set on any ManagedObject (including View) and provides several useful accessors related to the service metadata. In order to get the meta model, we need to use the appropriate API from the ODataModel instead of instantiating the model directly:
myODataModel.getMetaModel().loaded()
.then(() =>/* Do something with */myODataModel.getMetaModel()/*...*/);
Documentation: Meta Model for OData V2