TypeOrm - await lazy query vs tem.find - typeorm

Good morning everyone.
I have a question regarding the following snippet.
#Transaction()
fun(#TransactionManager() tem: EntityManager) {
const bird = await tem.findOne(Bird, "b1")
const worms = await bird.worms
// ...
}
It seems that await bird.worms triggers a query that doesn't run inside the transaction.
Am I correct ?
Should it be safe to assume that it uses the same transaction that was used to findOne.
Or does it use a standalone manager?
Thanks

Related

TypeORM relations in transaction

After reading TypeORM documentation, it is not clear to me, if it is safe to use lazy relations inside transactions. The documentation about transactions says:
All operations MUST be executed using the provided transactional entity manager.
Does it apply for loading related entities as well? When using lazy relations, can I do the following?
await dataSource.transaction(async (transactionalEntityManager) => {
const parentEntity = await transactionalEntityManager.findOneBy(ParentEntity, {
id: 1,
});
const childEntity = await parentEntity.child; // It works, but is it safe?
})
If not, what is the proper way of loading relations inside transactions? Thank you.

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!

different directory access in firebase realtime database for dialogflow fulfillment

I'm a newbie in node.js(firebase functions) and Dialogflow fulfillment, I want to retrieve data in a different directory. first is to check the nearest store, and then check the inventory of the store in a different directory, but I have a problem with return. so how I can fix it?
app.intent('location_checking - yes',(conv)=> {
var store= database.ref('store');
var inventory = database.ref('inventory);
var keystore=[];
return store.orderByKey().on("child_added", function(snapshot){
keystore.push(snapshot.key)
})
return inventory.child(keystore).on("value", function(snapshot){
var tomato =snapshot.val().tomato;
//and then check the nearest store with available stock
})
})
You have a few issues, some of them conceptual.
The first is that you're using on() and the "child_added" event. But since this is happening inside an Intent Handler, which only gets triggered when the user has done something, you can't also listen to conventional events and react to them. Instead, you should probably use once() with a "value" event - so you query for the values you want and work with them.
Second is that the Intent Handler expects you to return a Promise if you are doing any asynchronous operations - anything that would require a callback handler, for example. This would require some restructuring in how you make the calls to once(), so they return a Promise, and you take action in a .then() block. Since you can chain Promises together using .then(), you can make multiple calls this way.
I'm not sure that ordering by key will get you the "closest" store, but I'll ignore that for the moment to illustrate the rest of the code.
So that part of your code might look something like
return store.orderByKey().once("value")
.then( snapshot => {
// Handle the results
// ...
// Make the next query
return inventory.child( childKey ).once("value");
})
.then( snapshot => {
// Handle the inventory results
});
You can also do this with async/await by making your Intent Handler an async function and then calling await on the database calls. Possibly something like.
app.intent('location_checking - yes', async (conv) => {
const store= database.ref('store');
const inventory = database.ref('inventory);
//...
const storeSnapshot = await store.orderByKey().once("value");
// Do something with the store snapshot
const inventorySnapshot = await inventory.child( childKey ).once("value");
// Do stuff with the inventory snapshot
})

What is the purpose of `FutureOr`?

Dart offers a FutureOr class, that allows writing:
FutureOr<int> future;
future = 42; // valid
future = Future.value(42); // also valid
I would assume that FutureOr would be useful to remove the unnecessary delay caused by the event loop if the value can be read synchronously.
But that doesn't seem to be the case, as showcased by:
import 'dart:async';
void main() async {
print('START');
futureOrExample();
print('END');
}
void futureOrExample() async {
FutureOr<int> futureOr = 42;
print('before await');
await futureOr;
print('end await');
}
which prints:
START
before await
END
end await
when I would expect:
START
before await
end await
END
In that case, why does FutureOr (or more generally await 42) work this way?
Similarly, what's the purpose of FutureOr in that situation since it produces the same result as Future?
I know that I could use SynchronousFuture to achieve the desired result, but I'm just trying to understand what's the use of FutureOr.
The use of FutureOr, as introduced with Dart 2, is to allow you to provide either a value or a future at a point where the existing Dart 1 API allowed the same thing for convenience, only in a way that can be statically typed.
The canonical example is Future.then. The signature on Future<T> is Future<R> then<R>(FutureOr<R> action(T value), {Function onError}).
The idea is that you can have an action on the future's value which is either synchronous or asynchronous. Originally there was a then function which took a synchronous callback and a chain function which took an asynchronous callback, but that was highly annoying to work with, and in good Dart 1 style, the API was reduced to one then method which took a function returning dynamic, and then it checked whether it was a future or not.
In Dart 1 it was easy to allow you to return either a value or a future. Dart 2 was not as lenient, so the FutureOr type was introduced to allow the existing API to keep working. If we had written the API from scratch, we'd probably have done something else, but migrating the existing asynchronous code base to something completely different was not an option, so the FutureOr type was introduced as a type-level hack.
The await operation was also originally defined to work on any object, long before FutureOr existed. For consistency and smaller code, an await e where e evaluated to a non-future would wrap that value in a future and await that. It means that there is only one quick and reusable check on a value (is it a future, if not wrap it), and then the remaining code is the same. There is only one code-path.
If the await worked synchronously on non-Future values, there would have to be a synchronous code path running through the await, as well as an asynchronous path waiting for a future. That would potentially double the code size, for example when compiling to JavaScript (or worse, if there were more awaits in the same control flow, you could get exponential blow-up for a naive implementation). Even if you avoided that by just calling the continuation function synchronously, it would likely be confusing to some readers that an await would not introduce an asynchronous gap. A mistake around that can cause race conditions or things happening in the wrong order.
So, the original design, predating FutureOr, was to make all await operations actually wait.
The introduction of FutureOr did not change this reasoning, and even if it did, it would now be a breaking change to not wait in places where people expect their code to actually give time for other microtasks to run.
The await keyword always lock the function execution.
Writing:
await 42
Is equivalent to:
await Future.value(42)
The reason being:
This is how await works in Javascript
it makes the behavior of await consistent.
Now, what's the purpose of FutureOr then?
FutureOr was never intended as a way to potentially make await synchronous.
Instead, it is an implementation detail of Future.
Without FutureOr, writing the following would not compile:
Future(() {
return 42; // compile error, not a Future
});
Future<int> future;
future.then((value) {
return value * 2; // compile error, not a Future
});
Instead, we would have to wrap all values in a Future.value like so:
Future<int> future;
future.then((value) {
return Future.value(value * 2);
});
for those who are still confused
I found good explanation https://itnext.io/what-is-futureor-in-dart-flutter-681091162c57 without diving into details
This piece of code could explain the target and real use cases of FutureOr
abstract class IDBService {
FutureOr<String> fetch();
}
class FirebaseRemoteService extends IDBService {
#override
Future<String> fetch() async => await 'data';
}
class LocalHiveDbService extends IDBService {
#override
String fetch() => 'data';
}
so in implementations of IDBService
the return type can be Future or String at the same time now!
Coming late to the discussion.
Updating my Dart comprehension - pardon my C++/JS -ish approach.
Seems like this would be useful for singleton initiation. Consider following:
import 'dart:async';
class AClass {
static String _info = '';
static FutureOr<String> get info async {
if (_info.isEmpty) {
print('--> is empty...');
_info = await Future.delayed(Duration(seconds:2),
() => "I'm alive!!");
}
else {
print('--> not empty');
}
return _info;
}
}
Future<void> main() async {
String info = await AClass.info;
print('Fist call: ' + info);
info = await AClass.info;
print('Second call: ' + info);
}
It works as expected - in either case, whether the _info member has been instantiated or not, the getter returns a valid string.
It works fine if I just use a Future<String> specifier in the getter, too. The current implementation makes FutureOr seem mostly like a self-documentation exercise (can return a Future<String> or a String...)
But, even if await currently always locks the execution, a future update may allow it to work as expected, in which case using the FutureOr construct would anticipate updates.
(Aside: I imagine this example could be condensed using an Optional wrapping the _info member, but that's a different exercise...)
I needed to use FutureOr today. I wanted to call a function that might be asynchronously (not always).
String callbackOne() => "hello";
Future<String> callbackTwo() async => (await Future.delayed(Duration(seconds: 1),() => "This is a sentence"));
Problem
I can do getLengthOfResult(callbackOne), but not getLengthOfResult(callbackTwo). Conversely, if accept an async callback, I can't use the sync callback.
DartPad
Future<int> getLengthOfResult(String Function() callback) async {
return callback().length;
}
Solution
DartPad
Future<int> getLengthOfResult(FutureOr<String> Function() callback) async {
// I can await on callbackOne, even though it returns a String.
final result = await callback();
return result.length;
}
main() {
getLengthOfResult(callbackOne);
getLengthOfResult(callbackTwo);
}

How to do several asynchronous I/O actions in Dart cleanly (Isolates)?

In Dart, there is a concept of Isolates. I have an application (that I'm experimenting in Dart) that has lots of asynchronous IO where each call (they are database calls) are dependent on the previous one. So I have ended up in a nested callback hell.
I was wondering if Isolates could solve that nested callback soup, but it looks a bit verbose and I'm not sure if it fits it well.
There are also Generators proposed in the next ECMAScript Harmony which could solve these things, but how would you currently do lots of asynchronous IO in Dart in a clean way?
You can use Future's and Completers to chain work together. The following future returns the result of a 'ls' command from a process:
Future<String> fetch(String dir) {
final completer = new Completer();
Process process = new Process.start('ls', [dir]);
process.exitHandler = (int exitCode) {
StringInputStream stringStream = new StringInputStream(process.stdout);
stringStream.dataHandler = () {
String content = stringStream.read();
completer.complete(content);
process.close();
};
};
process.errorHandler = (var error) {
completer.completeException(error);
return true;
};
return completer.future;
};
which you can then chain together like this:
fetch('/').then((val) => fetch("/usr").then((val) => fetch("/tmp")));
Not the most pretty solution but this is what I get by with now.

Resources