Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion .llms-snapshots/llms-full.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7412,7 +7412,7 @@ Here is an example of an hook which fetches an API to get the link to an image o
Here is an example of an `onSetDoc` hook which fetches an API to get the link to an image of a dog and saves that information within the Datastore. While this might not be a practical real-world use case, it is simple enough to demonstrate the feature.

```
import { defineHook, type OnSetDoc, SetDoc } from "@junobuild/functions";import { j } from "@junobuild/schema";import { httpRequest, HttpRequestArgs } from "@junobuild/functions/ic-cdk";import { encodeDocData, setDocStore } from "@junobuild/functions/sdk";// The data of the document we are looking to update in the Satellite's Datastore.const DogDataSchema = j.strictObject({ src: j.string().optional()});// We are using the Dog CEO API in this example.// https://dog.ceo/dog-api///// Its endpoint "random" returns such JSON data:// {// "message": "https://images.dog.ceo/breeds/mountain-swiss/n02107574_1118.jpg",// "status": "success"// }//// That's why we declare a struct that matches the structure of the answer.const DogApiResponseSchema = j.strictObject({ message: j.url(), status: j.string()});export const onSetDoc = defineHook<OnSetDoc>({ collections: ["dogs"], run: async ({ caller, data: { collection, key, data: { after: { description, version } } } }) => { // 1. Prepare the HTTP GET request const url = "https://dog.ceo/api/breeds/image/random"; const args: HttpRequestArgs = { url, method: "GET", headers: [], // Use a single node as we do not require that a trust level for fetching a dog image for demo purposes. 😉 isReplicated: false }; // 2. Execute the HTTP request. const result = await httpRequest(args); // 3. Transform the response to a structured data object. const decoder = new TextDecoder(); const body = decoder.decode(result.body); const dogResponse = DogApiResponseSchema.parse(JSON.parse(body)); // 4. Our goal is to update the document in the Datastore with an update that contains the link to the image fetched from the API we just called. const dogData = DogDataSchema.parse({ src: dogResponse.message }); // 5. We encode those data back to blob because the Datastore holds data as blob. const encodedData = encodeDocData(dogData); // 6. Then we construct the parameters required to call the function that save the data in the Datastore. const doc: SetDoc = { description, version, data: encodedData }; // 7. We store the data in the Datastore for the same caller as the one who triggered the original on_set_doc, in the same collection with the same key as well. setDocStore({ caller, collection, key, doc }); }});
import { defineHook, type OnSetDoc, SetDoc } from "@junobuild/functions";import { j } from "@junobuild/schema";import { httpRequest, HttpRequestArgs } from "@junobuild/functions/ic-cdk";import { encodeDocData, setDocStore } from "@junobuild/functions/sdk";// The data of the document we are looking to update in the Satellite's Datastore.const DogDataSchema = j.strictObject({ src: j.string().optional()});// We are using the Dog CEO API in this example.// https://dog.ceo/dog-api///// Its endpoint "random" returns such JSON data:// {// "message": "https://images.dog.ceo/breeds/mountain-swiss/n02107574_1118.jpg",// "status": "success"// }//// That's why we declare a struct that matches the structure of the answer.const DogApiResponseSchema = j.strictObject({ message: j.url(), status: j.string()});export const onSetDoc = defineHook<OnSetDoc>({ collections: ["dogs"], run: async ({ caller, data: { collection, key, data: { after: { description, version } } } }) => { // 1. Prepare the HTTP GET request const url = "https://dog.ceo/api/breeds/image/random"; const args: HttpRequestArgs = { url, method: "GET", // Use a single node as we do not require that a trust level for fetching a dog image for demo purposes. 😉 isReplicated: false }; // 2. Execute the HTTP request. const result = await httpRequest(args); // 3. Transform the response to a structured data object. const decoder = new TextDecoder(); const body = decoder.decode(result.body); const dogResponse = DogApiResponseSchema.parse(JSON.parse(body)); // 4. Our goal is to update the document in the Datastore with an update that contains the link to the image fetched from the API we just called. const dogData = DogDataSchema.parse({ src: dogResponse.message }); // 5. We encode those data back to blob because the Datastore holds data as blob. const encodedData = encodeDocData(dogData); // 6. Then we construct the parameters required to call the function that save the data in the Datastore. const doc: SetDoc = { description, version, data: encodedData }; // 7. We store the data in the Datastore for the same caller as the one who triggered the original on_set_doc, in the same collection with the same key as well. setDocStore({ caller, collection, key, doc }); }});
```

As with the previous example, the hook will asynchronously update the document. If you wait a bit before retrieving the document in your frontend, you might notice that the source of the image has been updated by your hook.
Expand Down Expand Up @@ -12820,6 +12820,42 @@ function call<T>(params: CallParams): Promise<T | undefined>;

---

## httpRequest

Performs an HTTP request from a Juno serverless function.

```
function httpRequest(args: HttpRequestArgs): Promise<HttpRequestResult>;
```

📦 Import from `@junobuild/functions/ic-cdk`

#### Parameters:

* `args`: The HTTP request parameters.
* `url`: The requested URL.
* `method`: The HTTP method — `GET`, `POST`, or `HEAD`.
* `headers` (optional): A list of HTTP request headers.
* `body` (optional): The request body as a `Uint8Array`.
* `maxResponseBytes` (optional): The maximal size of the response in bytes.
* `transform` (optional): The name of a query function used to transform the response before consensus. If provided, a corresponding query must be declared using `defineQuery`.
* `isReplicated` (optional): Whether all nodes should perform the request and agree on the response, or just one node. Defaults to all nodes if not specified.

#### Returns:

* `Promise<HttpRequestResult>`: A promise resolving to the HTTP response, containing `status` (bigint), `headers`, and `body` (Uint8Array).

#### Throws:

* `ZodError` if the provided arguments do not match the expected schema.
* `Error` if the HTTP request fails.

#### Notes:

* This function is a JavaScript binding for the Rust function [ic\_cdk::management\_canister::http\_request()](https://docs.rs/ic-cdk/0.19.0/ic_cdk/management_canister/fn.http_request.html).

---

## msgCaller

Returns the Principal ID of the caller of the current function.
Expand Down
36 changes: 36 additions & 0 deletions docs/reference/functions/typescript/ic-cdk.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,42 @@ function call<T>(params: CallParams): Promise<T | undefined>;

---

## httpRequest

Performs an HTTP request from a Juno serverless function.

```typescript
function httpRequest(args: HttpRequestArgs): Promise<HttpRequestResult>;
```

📦 Import from `@junobuild/functions/ic-cdk`

#### Parameters:

- `args`: The HTTP request parameters.
- `url`: The requested URL.
- `method`: The HTTP method — `GET`, `POST`, or `HEAD`.
- `headers` (optional): A list of HTTP request headers.
- `body` (optional): The request body as a `Uint8Array`.
- `maxResponseBytes` (optional): The maximal size of the response in bytes.
- `transform` (optional): The name of a query function used to transform the response before consensus. If provided, a corresponding query must be declared using `defineQuery`.
- `isReplicated` (optional): Whether all nodes should perform the request and agree on the response, or just one node. Defaults to all nodes if not specified.

#### Returns:

- `Promise<HttpRequestResult>`: A promise resolving to the HTTP response, containing `status` (bigint), `headers`, and `body` (Uint8Array).

#### Throws:

- `ZodError` if the provided arguments do not match the expected schema.
- `Error` if the HTTP request fails.

#### Notes:

- This function is a JavaScript binding for the Rust function [ic_cdk::management_canister::http_request()](https://docs.rs/ic-cdk/0.19.0/ic_cdk/management_canister/fn.http_request.html).

---

## msgCaller

Returns the Principal ID of the caller of the current function.
Expand Down