You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Serverless Functions are triggered by hooks, which respond to events occurring in the Satellite, such as setting a document. Before implementing a hook that manipulates data ("backend"), let's first set up a JavaScript function in your ("frontend") dApp.
1
+
Hooks respond to events occurring in your Satellite, such as a document being created or updated. They run automatically in the background and are not invoked directly.
2
2
3
-
Define a setter function in your frontend dApp as follows:
4
-
5
-
```typescript
6
-
interfaceExample {
7
-
hello:string;
8
-
}
9
-
10
-
let key:string|undefined;
11
-
12
-
const set =async () => {
13
-
key=crypto.randomUUID();
14
-
15
-
const record =awaitsetDoc<Example>({
16
-
collection: "demo",
17
-
doc: {
18
-
key,
19
-
data: {
20
-
hello: "world"
21
-
}
22
-
}
23
-
});
24
-
25
-
console.log("Set done", record);
26
-
};
27
-
```
28
-
29
-
This code generates a key and persists a document in a collection of the Datastore named "demo".
30
-
31
-
Additionally, add a getter to your code:
32
-
33
-
```typescript
34
-
const get =async () => {
35
-
if (key===undefined) {
36
-
return;
37
-
}
38
-
39
-
const record =awaitgetDoc({
40
-
collection: "demo",
41
-
key
42
-
});
43
-
44
-
console.log("Get done", record);
45
-
};
46
-
```
47
-
48
-
Without a hook, executing these two operations one after the other would result in a record containing "hello: world".
3
+
The following example declares a hook that listens to changes in the `demo` collection and modifies the document's data before saving it back:
As outlined in the [Quickstart](#quickstart) chapter, run `juno emulator build` to compile and deploy the code locally.
100
+
:::note
101
+
102
+
Hooks execute asynchronously, separate from the request-response cycle. Changes made by a hook will not be immediately visible to the caller.
103
103
104
-
When testing this feature, if you wait a bit before calling the getter, unlike in the previous step, you should now receive the modified "hello: world checked" text set by the hook. This delay occurs because serverless Functions run fully asynchronously from the request-response between your frontend and the Satellite.
104
+
:::
105
105
106
106
---
107
107
@@ -137,7 +137,7 @@ This example ensures that any document added to the <code>notes</code> collectio
137
137
138
138
---
139
139
140
-
## Calling Canisters on ICP
140
+
## Calling Other Canisters
141
141
142
142
You can make calls to other canisters on the Internet Computer directly from your serverless functions using `ic_cdk::call`.
Once saved, your code should be automatically compiled and deployed.
79
+
:::note
84
80
85
-
When testing this feature, if you wait a bit before calling the getter, you should now receive the modified "hello: world checked" text set by the hook. This delay occurs because serverless Functions execute fully asynchronously, separate from the request-response cycle between your frontend and the Satellite.
81
+
Hooks execute asynchronously, separate from the request-response cycle. Changes made by a hook will not be immediately visible to the caller.
86
82
87
-
---
83
+
:::
88
84
89
-
##Assertions
85
+
### Handling Multiple Collections
90
86
91
-
Assertions allow you to validate or reject operations before they are executed. They're useful for enforcing data integrity, security policies, or business rules inside your Satellite, and they run synchronously during the request lifecycle.
87
+
If your hook applies to many collections, a switch statement is one way to route logic:
This example ensures that any document added to the <code>notes</code> collection does not contain the word <code>"hello"</code> (case-insensitive). If it does, the operation is rejected before the data is saved.
134
+
This ensures all collections are handled and you'll get a TypeScript error if one is missing.
114
135
115
136
---
116
137
117
-
### Validating with Zod
138
+
## Custom Functions
139
+
140
+
Custom Functions let you define callable endpoints directly inside your Satellite. Unlike hooks, which react to events, custom functions are explicitly invoked - from your frontend or from other modules.
118
141
119
-
To simplify and strengthen your assertions, we recommend using [Zod](https://zod.dev/) — a TypeScript-first schema validation library. It's already bundled as a dependency of the `@junobuild/functions` package, so there's nothing else to install.
142
+
You define them using `defineQuery` or `defineUpdate`, describe their input and output shapes with the `j` type system, and Juno takes care of generating all the necessary bindings under the hood.
120
143
121
-
Here's how you can rewrite your assertion using Zod for a cleaner and more declarative approach:
144
+
### Query vs. Update
145
+
146
+
A **query** is a read-only function. It returns data without modifying any state. Queries are fast and suitable for fetching or computing information.
147
+
148
+
An **update** is a function that can read and write state. Use it when your logic needs to persist data or trigger side effects. Updates can also be used for read operations when the response needs to be certified - making them suitable for security-sensitive use cases where data integrity must be guaranteed.
149
+
150
+
### Defining a Function
151
+
152
+
Describe your function's input and output shapes using the `j` type system, then pass them to `defineQuery` or `defineUpdate` along with your handler:
Handlers can be synchronous or asynchronous. Both `args` and `returns` are optional.
174
+
175
+
### Calling from the Frontend
176
+
177
+
When you build your project, a type-safe client API is automatically generated based on your function definitions. You can import and call your functions directly from your frontend without writing any glue code:
Assertions allow you to validate or reject operations before they are executed. They're useful for enforcing data integrity, security policies, or business rules inside your Satellite, and they run synchronously during the request lifecycle.
const data =decodeDocData<NoteData>(context.data.data.proposed.data);
145
-
noteSchema.parse(data);
203
+
204
+
if (data.text.toLowerCase().includes("hello")) {
205
+
thrownewError("The text must not include the word 'hello'");
206
+
}
146
207
}
147
208
});
148
209
```
149
210
150
-
This approach is more expressive, easier to extend, and automatically gives you type safety and error messaging. If the validation fails, `parse()` will throw and reject the request.
211
+
This example ensures that any document added to the `notes` collection does not contain the word `"hello"` (case-insensitive). If it does, the operation is rejected before the data is saved.
151
212
152
213
---
153
214
154
-
## Calling Canisters on ICP
215
+
## Calling Other Canisters
155
216
156
217
importCallfrom"./components/functions/call.md";
157
218
@@ -211,57 +272,23 @@ The `args` field contains a tuple with the Candid type definition and the corres
211
272
212
273
The `call` function handles both encoding the request and decoding the response using the provided types.
213
274
214
-
To encode and decode these calls, you need JavaScript structures that match the Candid types used by the target canister. Currently, the best (and slightly annoying) way to get them is to copy/paste from the `service` output generated by tools like `didc`. It's not ideal, but that’s the current status. We’ll improve this in the future — meanwhile, feel free to reach out if you need help finding or shaping the types.
275
+
To encode and decode these calls, you need JavaScript structures that match the Candid IDL types used by the target canister.
215
276
216
277
---
217
278
218
-
## Handling Multiple Collections
219
-
220
-
If your hook applies to many collections, a switch statement is one way to route logic:
The `j` type system is Juno's schema layer for custom functions. It is built on top of [Zod](https://zod.dev/) and extends it with types specific to the Juno and Internet Computer environment, such as `j.principal()`.
239
282
240
-
While this works, you might accidentally forget to handle one of the observed collections. To prevent that, you can use a typed map:
283
+
You use it to describe the shape of your function's arguments and return value. These schemas are both validated at runtime and used at build time to generate the necessary types and bindings.
0 commit comments