Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pages through Style guide #16330

Merged
merged 3 commits into from
Aug 20, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,8 @@ tags:
- Hono
languages:
- JavaScript

---



This tutorial will teach you how to use [R2](/r2/) as a static asset bucket for your [Pages](/pages/) app. This is especially helpful if you're hitting the [file limit](/pages/platform/limits/#files) or the [max file size limit](/pages/platform/limits/#file-size) on Pages.

To illustrate how this is done, we will use R2 as a static asset storage for a fictional cat blog.
Expand Down Expand Up @@ -42,7 +39,7 @@ Adding more videos and images to the blog would be great, but our asset size is

The first step is creating an R2 bucket to store the static assets. A new bucket can be created with the dashboard or via Wrangler.

Using the dashboard, navigate to the R2 tab, then click on *Create bucket.* We will name the bucket for our blog *cat-media*. Always remember to give your buckets descriptive names:
Using the dashboard, navigate to the R2 tab, then click on *Create bucket.* We will name the bucket for our blog _cat-media_. Always remember to give your buckets descriptive names:

![Dashboard](~/assets/images/pages/tutorials/pages-r2/dash.png)

Expand Down Expand Up @@ -80,18 +77,18 @@ bucket_name = "cat-media"

:::note

Note: The keyword `ASSETS` is reserved and cannot be used as a resource binding.
Note: The keyword `ASSETS` is reserved and cannot be used as a resource binding.
:::

Save `wrangler.toml` and we are ready to move on to the last step.

Alternatively, you can add a binding to your Pages project on the dashboard by navigating to the project’s *Settings* tab > *Functions* > *R2 bucket bindings*.
Alternatively, you can add a binding to your Pages project on the dashboard by navigating to the project’s _Settings_ tab > _Functions_ > _R2 bucket bindings_.

## Serve R2 Assets From Pages

The last step involves serving media assets from R2 on the blog. To do that, we will create a function to handle requests for media files.

In the project folder, create a *functions* directory. Then, create a *media* subdirectory and a file named `[[all]].js` in it. All HTTP requests to `/media` will be routed to this file.
In the project folder, create a _functions_ directory. Then, create a _media_ subdirectory and a file named `[[all]].js` in it. All HTTP requests to `/media` will be routed to this file.

After creating the folders and JavaScript file, the blog directory structure should look like:

Expand All @@ -114,12 +111,12 @@ Finally, we will add a handler function to `[[all]].js`. This function receives

```js
export async function onRequestGet(ctx) {
const path = new URL(ctx.request.url).pathname.replace("/media/", "");
const file = await ctx.env.MEDIA.get(path);
if (!file) return new Response(null, { status: 404 });
return new Response(file.body, {
headers: { "Content-Type": file.httpMetadata.contentType },
});
const path = new URL(ctx.request.url).pathname.replace("/media/", "");
const file = await ctx.env.MEDIA.get(path);
if (!file) return new Response(null, { status: 404 });
return new Response(file.body, {
headers: { "Content-Type": file.httpMetadata.contentType },
});
}
```

Expand All @@ -130,22 +127,22 @@ Before deploying the changes made so far to our cat blog, let us add a few new p
```html
<!doctype html>
<html lang="en">
<body>
<h1>Awesome Cat Blog! 😺</h1>
<p>Today's post:</p>
<video width="320" controls>
<source src="/media/videos/video1.mp4" type="video/mp4" />
</video>
<p>Yesterday's post:</p>
<img src="/media/images/cat1.jpg" width="320" />
</body>
<body>
<h1>Awesome Cat Blog! 😺</h1>
<p>Today's post:</p>
<video width="320" controls>
<source src="/media/videos/video1.mp4" type="video/mp4" />
</video>
<p>Yesterday's post:</p>
<img src="/media/images/cat1.jpg" width="320" />
</body>
</html>
```

With all the files saved, open a new terminal window to deploy the app:

```sh
$ npm run deploy
npm run deploy
```

Once deployed, media assets are fetched and served from the R2 bucket.
Expand All @@ -154,6 +151,6 @@ Once deployed, media assets are fetched and served from the R2 bucket.

## **Related resources**

* [Learn how function routing works in Pages.](/pages/functions/routing/)
* [Learn how to create public R2 buckets](/r2/buckets/public-buckets/).
* [Learn how to use R2 from Workers](/r2/api/workers/workers-api-usage/).
- [Learn how function routing works in Pages.](/pages/functions/routing/)
- [Learn how to create public R2 buckets](/r2/buckets/public-buckets/).
- [Learn how to use R2 from Workers](/r2/api/workers/workers-api-usage/).
57 changes: 28 additions & 29 deletions src/content/docs/pub-sub/examples/connect-javascript.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ pcx_content_type: reference
type: example
summary: Use MQTT.js with the token authentication mode configured on a broker.
description: Use MQTT.js with the token authentication mode configured on a broker.

---

Below is an example using [MQTT.js](https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options) with the TOKEN authentication mode configured on a broker. The example assumes you have [Node.js](https://nodejs.org/en/) v16 or higher installed on your system.
Expand All @@ -19,7 +18,7 @@ Before running the example, make sure to install the MQTT library:

```sh
# Pre-requisite: install MQTT.js
$ npm install mqtt --save
npm install mqtt --save
```

Copy the following example as `example.js` and run it with `node example.js`.
Expand All @@ -40,50 +39,50 @@ let topic = check_env(process.env.BROKER_TOPIC);

// Configure and create the MQTT client
const client = mqtt.connect(uri, {
protocolVersion: 5,
port: 8883,
clean: true,
connectTimeout: 2000, // 2 seconds
clientId: "",
username,
password,
protocolVersion: 5,
port: 8883,
clean: true,
connectTimeout: 2000, // 2 seconds
clientId: "",
username,
password,
});

// Emit errors and exit
client.on("error", function (err) {
console.log(`⚠️ error: ${err}`);
client.end();
process.exit();
console.log(`⚠️ error: ${err}`);
client.end();
process.exit();
});

// Connect to your broker
client.on("connect", function () {
console.log(`🌎 connected to ${process.env.BROKER_URI}!`);
// Subscribe to a topic
client.subscribe(topic, function (err) {
if (!err) {
console.log(`✅ subscribed to ${topic}`);
// Publish a message!
client.publish(topic, "My first MQTT message");
}
});
console.log(`🌎 connected to ${process.env.BROKER_URI}!`);
// Subscribe to a topic
client.subscribe(topic, function (err) {
if (!err) {
console.log(`✅ subscribed to ${topic}`);
// Publish a message!
client.publish(topic, "My first MQTT message");
}
});
});

// Start waiting for messages
client.on("message", async function (topic, message) {
console.log(`received a message: ${message.toString()}`);
console.log(`received a message: ${message.toString()}`);

// Goodbye!
client.end();
process.exit();
// Goodbye!
client.end();
process.exit();
});

// Return variable or throw error
function check_env(env) {
if (!env) {
throw "BROKER_URI, BROKER_TOKEN and BROKER_TOPIC must be set.";
}
if (!env) {
throw "BROKER_URI, BROKER_TOKEN and BROKER_TOPIC must be set.";
}

return env;
return env;
}
```
9 changes: 4 additions & 5 deletions src/content/docs/pub-sub/examples/connect-python.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ pcx_content_type: reference
type: example
summary: Connect to a Broker using Python 3
description: Connect to a Broker using Python 3

---

Below is an example using the [paho.mqtt.python](https://github.com/eclipse/paho.mqtt.python) package with the TOKEN authentication mode configured on a Broker.
Expand All @@ -13,15 +12,15 @@ The example below creates a simple subscriber, sends a message to the configured

Make sure to set environmental variables for the following before running the example:

* `BROKER_FQDN` - e.g. `YOUR-BROKER.YOUR-NAMESPACE.cloudflarepubsub.com` without the port or `mqtts://` scheme
* `BROKER_TOKEN` (a valid auth token)
* `BROKER_TOPIC` - e.g. `test/topic` or `hello/world`
- `BROKER_FQDN` - e.g. `YOUR-BROKER.YOUR-NAMESPACE.cloudflarepubsub.com` without the port or `mqtts://` scheme
- `BROKER_TOKEN` (a valid auth token)
- `BROKER_TOPIC` - e.g. `test/topic` or `hello/world`

The example below uses Python 3.8, but should run on Python 3.6 and above.

```sh
# Ensure you have paho-mqtt installed
$ pip3 install paho-mqtt
pip3 install paho-mqtt
```

Create a file called `pubsub.py` with the following content, and use `python3 pubsub.py` to run the example:
Expand Down
Loading
Loading