Twilio functions calling other Twilio functions - twilio

My Twilio function is in danger of getting too large and unwieldy. I'd like to break it up into smaller functions, and have the 'master' function call the other functions to get data as needed.
I don't see anything in the documentation about this, and the few tests I've tried have not been successful. Is there an easy/best way to go about doing this? Thanks!

this is an example of how to include code from another function:
including function's body
exports.handler = function(context, event, callback) {
let path = Runtime.getFunctions().helper.path;
let helper = require(path);
let output = helper.output_init();
}
included function's body (the name of this function needs to be 'helper' to work on this example)
function output_init(){
let output = new Twilio.Response();
output.setStatusCode(200);
output.appendHeader('Content-Type', 'application/json');
return output;
}
module.exports ={
output_init: output_init,
};
hope this helps

there is a discussion around this topic on a Google Groups forum and the details are provided from the documentation below:
Runtime Client
https://www.twilio.com/docs/runtime/client#functions
"The Function object enables developers to compose complex applications by allowing them to include and execute code stored in multiple Functions."

Related

WebRtc connection in dart:html, incomplete API?

What would be the equivalent in dart of the following javascript snippet?
myPeerConnection.createOffer().then(function(offer) {
return myPeerConnection.setLocalDescription(offer);
})
The straight translation:
final offer = await myPeerConnection.createOffer();
myPeerConnection.setLocalDescription(offer);
does not compile because createOffer() eventually returns a RtcSessionDescription and setLocalDescription accepts only a Map.
And RtcSessionDescription does not have a nice way to convert to a Map in the API.
Am I missing anything? Thanks!
After trying a few things, this works in my use case (at least in Chrome):
final offer = await myPeerConnection.createOffer();
myPeerConnection.setLocalDescription({"sdp": offer.sdp, "type": offer.type ?? 'offer'});

How to call a Function from a Function in Twilio Serverless?

I'm trying to see about using Twilio Serverless to replace my IVR. I would like to have some centralized functions to use within the functions.
For example, My main may be something like /MainMenu, which will have all the Twml.
but it will also need to call a function like /LogStats, which will be a function that does a REST Call to my API to collect Stats.
I'd appreciate your guidance in this. I'm also a little confused about why there's a Functions Classic, and a Functions Services. Am I to assume that Functions Classic will go away?
Thanks
Update from comments
Hi Lizzie, thanks for your response. I have it working with the zoltar example.. but when I try to use it for creating a call to a REST API, it's not consistently calling the API.. Any Ideas?
Here's what I'm talking about..
const axios = require('axios');
const log = {
ask: async function(event){
try{
const res = await axios.post('https://myid.ngrok.io/api/calllogger/lognewcall', {
CallSid: event.CallSid,
Caller: event.Caller,
App: "EmgLine",
CallerCity: event.CallerCity,
CallerState: event.CallerState
});
if(!res.ok){
throw new Error(`HTTP error! Status ${res.status}`);
}
const data = await res.Message;
return data;
} catch(err){
const errMessage = `test: ${err}`;
return errMessage;
}
}
};
module.exports = log;
Twilio developer evangelist here.
The Functions Classic are the older Functions with the older Functions UI. It still works, but Functions Services are newer and recommended to use. A Service is an application container to store all your Functions and Assets, and used to manage deployments and separate environments. You will likely create a new Service for each new project you work on.
You can use code from another Function in another Function with code like this
exports.handler = function (context, event, callback) {
// First, get the path for the Function. Note that the key of the function
// is not preceded by a "/" as is the case with Assets
const zoltarPath = Runtime.getFunctions()['zoltar'].path;
// Next, use require() to import the library
const zoltar = require(zoltarPath);
// Finally, use the module as you would any other!
console.log('The answer to your riddle is: ' + zoltar.ask());
return callback();
}
Let me know if this helps at all!

Can I use more than one mutation function in GP?

I want to use more than one mutation method in GP, for example both mutUniform and mutEmphemeral. But all the algorithm can only receive one parameter. Is there method can solve this?
Assuming you have already defined mutUniform and mutEmphemeral, you can define a new mutation function that runs both mutations, and register that new function to your toolbox.
This would look something along the lines of
def mutMyWay(individual, mutpb, uniform_parameters, emphemeral_parameters):
if random.random()<mutpb:
individual = mutUniform(individual, *uniform_parameters)
individual = mutEmphemeral(individual, *emphemeral_parameters)
toolbox.register('mutate', mutMyWay)

Fable F# to Javascript: Parameterless functions being given a parameter when referenced

I am having difficulty referring to parameterless functions in Fable.
With this example:
let f1 () =
1
let someRefTof1 = f1
I'd expect the generated js to look something like this:
function f1() {
return 1;
}
var someRefTof1 = f1;
but what I actually get is:
function f1() {
return 1;
}
var someRefTof1 = exports.someRefTof1 = function someRefTof1(arg00_) {
return f1(arg00_);
};
I'm unclear on the purpose of arg00_ or how to avoid it being generated?
(As a bit of background, I am struggling to call a function in an external js library which expects a function to be passed as a parameter)
Edit:
Background
The above is what i believe to be a minimal, verifiable, reproduction of my question but, after comments, I thought it may be useful to provide a touch more context on why this is causing issues. What I am actually trying to do is use angularjs from Fable.
So my example looks more like this:
let app = AngularFable.NgFable.angular.``module``("app",[||])
type TestCtrl() =
member this.Val1() = "boom";
app?controller("test", TestCtrl)
which gets compiled to:
var app = exports.app = angular.module("app", []);
var TestCtrl = exports.TestCtrl = function () {
function TestCtrl() {
_classCallCheck(this, TestCtrl);
}
TestCtrl.prototype.Val1 = function Val1() {
return "boom";
};
return TestCtrl;
}();
_fableCore.Util.setInterfaces(TestCtrl.prototype, [], "App.TestCtrl");
app.controller("test", function (unitVar) {
return new TestCtrl();
});
with unitVar being the problematic parameter introduced in this example. When I use this in my html with something like:
<div ng-app="app">
<div ng-controller="test as vm">
{{vm.Val1()}}
</div>
</div>
I run into an unknown provider error whereas if I simply change the compiled javascript to remove the unitVar parameter from the last line like this:
app.controller("test", function () {
return new TestCtrl();
});
then my example works as expected.
I'd really like to know if there is a way to avoid having the Fable compiler generate this parameter. I'm 99% sure this reduces to the same problem as in my original question but I've included this additional context to better explain why this is an issue
Thank you very much for your question and detailed explanations. There're two things here that are a bit tricky and are caused by optimisations both of the F# compiler and Fable.
In the AST provided by the F# compiler, methods (functions that are members of a type or module) are compiled as usual methods as in C#. This is for optimization.
However, when you create an anonymous lambda or make a reference to a method, the F# compiler will keep F# semantics, that is, all functions have a single argument (as John Palmer says, unit is an argument too) and can be curried.
Ok, this info is just to make clear why the F# compiler/Fable represent methods and lambdas differently. Let's go with the issue of argumentless functions: the obvious solution would be of course to remove the F# compiler generated argument for functions accepting unit (as it's already done for methods). In fact, I also had problems with libraries like Mocha because of this.
I did try to remove the unit argument at the beginning but I got fails in some scenarios because of this. TBH, I don't remember now exactly which tests were failing but because of the expectation that there'll be always an argument, in some cases function composition or inlining was failing when the unit argument was removed.
Other attempts to modify the semantics of F# functions in the JS runtime have always failed because they don't cover all scenarios. However, we can be more lenient with delegates (System.Func<>) as it's usually safe to assume these ones should behave more like functions in languages like C# or F#. I can try to remove the unit argument just for delegates and see what happens :)
For more info about sending F# functions to JS code you can check the documentation.
UPDATE: Scratch all that, please try fable-compiler#0.6.12 and fable-core#0.6.8. This version eliminates unit arguments, the solution was actually simpler than I thought and (hopefully) shouldn't create issues with existing projects. (The explanation about methods and lambdas compiled differently still applies.)

Is there a more elegant way to handle HttpRequest body content in Dart?

With the release of the new dart:io libraries, in order to read the data from an HttpRequest we now need to:
Listen to the body to handle data and notified of it's completion.
In order to accomplish this, I've been using something similar to the following to get all of the data from the request (taken from the dart:io tests):
List<int> body = new List<int>();
request.listen(body.addAll, onDone: () {
var str = new String.fromCharCodes(body);
// Now do something with the string of data
});
Is there some way of using transform and/or StringDecoders to already provide a constructed result. The only way I can think of, I would still need to create a StringBuffer and use writeAll to ensure all data is passed in the event it doesn't all arrive at once, and still call the onDone before using the string in the buffer.
So I guess ultimately the question is: is there some way I can use a HttpRequest (or in all actuality any Stream) without needing to buffer/build the results and can just pass a callback or handler which receives the entire contents?
I haven't tried this, but I think you should be able to use StringDecoder, toList() and join() to get the whole body:
request.transform(new StringDecoder()).toList().then((data) {
var body = data.join('');
print(body);
}

Resources