Skip to content

Commit 71cacae

Browse files
authored
chore: Add basic example (#26)
* add basic example * update readme's
1 parent 8e85fe6 commit 71cacae

File tree

8 files changed

+576
-2
lines changed

8 files changed

+576
-2
lines changed

examples/basic_example/README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# basic_example
2+
3+
This example showcases how to use the runtime with basic js functions.
4+
5+
## Install the runtime
6+
7+
- `dart pub global activate globe_cli`
8+
9+
- `globe runtime install`
10+
11+
## Run the code
12+
13+
- `dart run lib/basic_example.dart`
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import 'dart:async';
2+
import 'dart:convert';
3+
import 'dart:io';
4+
5+
import 'package:globe_runtime/globe_runtime.dart';
6+
import 'package:path/path.dart' as path;
7+
8+
const moduleName = 'BasicExample';
9+
10+
Future<List<int>> callJsFunction(
11+
String functionName, {
12+
List<FFIConvertible> args = const [],
13+
}) async {
14+
final completer = Completer<List<int>>();
15+
GlobeRuntime.instance.callFunction(
16+
moduleName,
17+
function: functionName,
18+
args: args,
19+
onData: (data) {
20+
if (data.hasError()) {
21+
completer.completeError(data.error);
22+
} else {
23+
completer.complete(data.data);
24+
}
25+
return true;
26+
},
27+
);
28+
return completer.future;
29+
}
30+
31+
void main() async {
32+
final runtime = GlobeRuntime.instance;
33+
final jsCodePath =
34+
path.join(Directory.current.path, 'lib', 'basic_example.js');
35+
36+
await runtime.registerModule(
37+
moduleName,
38+
jsCodePath,
39+
args: ['100'.toFFIType],
40+
);
41+
42+
final result = await callJsFunction(
43+
'fetch_url',
44+
args: ['https://jsonplaceholder.typicode.com/todos/1'.toFFIType],
45+
).then((data) => JsonPayload(data: data).unpack());
46+
stdout.writeln(JsonEncoder.withIndent(' ').convert(result));
47+
48+
exit(0);
49+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const sdk = {
2+
init: function (apiKey) {
3+
return { apiKey };
4+
},
5+
functions: {
6+
fetch_url: async function (_, url, DartCallbackId) {
7+
try {
8+
const response = await fetch(url);
9+
10+
const data = await response.json();
11+
12+
const encoded = JsonPayload.encode(data);
13+
if (!encoded) {
14+
Dart.send_error(DartCallbackId, "Failed to encode response");
15+
return;
16+
}
17+
18+
Dart.send_value(DartCallbackId, encoded);
19+
} catch (err) {
20+
Dart.send_error(DartCallbackId, `Fetch failed: ${err.message}`);
21+
}
22+
},
23+
},
24+
};
25+
26+
export default sdk;

0 commit comments

Comments
 (0)