### Start the application Source: https://github.com/denoland/examples/blob/main/with-react/readme.md Execute the start task to run the React application. ```bash deno task start ``` -------------------------------- ### Start the API server Source: https://github.com/denoland/examples/blob/main/with-react/readme.md Run the Oak server with the required network and environment permissions. ```sh deno run --allow-env --allow-net api/main.ts ``` -------------------------------- ### Launch Apollo server Source: https://github.com/denoland/examples/blob/main/with-apollo/README.md Configure and start the server in main.ts. ```tsx import { ApolloServer } from "npm:@apollo/server@^4.1"; import { startStandaloneServer } from "npm:@apollo/server/standalone@4.1"; import { graphql } from "npm:graphql@16.6"; import { typeDefs } from "./schema.ts"; import { resolvers } from "./resolvers.ts"; const server = new ApolloServer({ typeDefs, resolvers, }); const { url } = await startStandaloneServer(server, { listen: { port: 8000 }, }); console.log(`Server running on: ${url}`); ``` -------------------------------- ### Start development server Source: https://github.com/denoland/examples/blob/main/with-fresh/README.md Executes the development task to watch the project directory and restart automatically. ```bash deno task dev ``` -------------------------------- ### Initialize Fastify server Source: https://github.com/denoland/examples/blob/main/with-fastify/readme.md Basic setup for a Fastify server listening on port 8000. ```typescript import Fastify, { type FastifyReply, type FastifyRequest, } from "npm:fastify@5.0.0"; const fastify = Fastify(); fastify.get("/", (_req: FastifyRequest, reply: FastifyReply) => { reply.send("Welcome to the Dinosaur API!"); }); await fastify.listen({ port: 8000 }); ``` -------------------------------- ### Initialize Express server Source: https://github.com/denoland/examples/blob/main/with-express/readme.md Basic setup for an Express application listening on port 8000. ```typescript import express from "npm:express@4.18.2"; const app = express(); app.get("/", (req, res) => { res.send("Welcome to the Dinosaur API!"); }); app.listen(8000); ``` -------------------------------- ### Run Docker Container on Droplet Source: https://github.com/denoland/examples/blob/main/on-digital-ocean/readme.md Pulls the image from the registry and starts the container on a Digital Ocean Droplet with port mapping and restart policies. ```bash docker run -d --restart always -it -p 8000:8000 --name deno-image registry.digitalocean.com/deno-on-digital-ocean/deno-image:new ``` -------------------------------- ### GET /users/ Source: https://github.com/denoland/examples/blob/main/with-oak-deno-kv/readme.md Retrieves a list of all users. ```APIDOC ## GET /users/ ### Description Retrieves all users from the database. ### Method GET ### Endpoint /users/ ``` -------------------------------- ### Retrieve all users Source: https://github.com/denoland/examples/blob/main/with-oak-deno-kv/readme.md Fetch the list of all users via a GET request. ```http GET /users/ ``` ```bash curl https://localhost:8000/users ``` -------------------------------- ### Query Result Format Source: https://github.com/denoland/examples/blob/main/with-mysql2/README.md Example of the data structure returned by a SELECT query. ```tsx [ [ { id: 1, name: "Aardonyx", description: "An early stage in the evolution of sauropods." }, { id: 2, name: "Abelisaurus", description: `Abel's lizard" has been reconstructed from a single skull.` }, { id: 3, name: "Deno", description: "The fastest dinosaur that ever lived." } ], ``` -------------------------------- ### GraphQL queries and responses Source: https://github.com/denoland/examples/blob/main/with-apollo/README.md Example queries to fetch dinosaur data and their corresponding JSON responses. ```graphql query { dinosaurs { name description } } ``` ```json { "data": { "dinosaurs": [ { "name": "Aardonyx", "description": "An early stage in the evolution of sauropods." }, { "name": "Abelisaurus", "description": "\"Abel's lizard\" has been reconstructed from a single skull." } ] } } ``` ```graphql query { dinosaur(name:"Aardonyx") { name description } } ``` ```json { "data": { "dinosaur": { "name": "Aardonyx", "description": "An early stage in the evolution of sauropods." } } } ``` -------------------------------- ### GET /users/email/:email Source: https://github.com/denoland/examples/blob/main/with-oak-deno-kv/readme.md Retrieves a user by their email address. ```APIDOC ## GET /users/email/:email ### Description Retrieves a user by their email address. ### Method GET ### Endpoint /users/email/:email ### Parameters #### Path Parameters - **email** (string) - Required - The email address of the user ``` -------------------------------- ### Single Row Result Source: https://github.com/denoland/examples/blob/main/with-mysql2/README.md Example output for a query returning a single row. ```tsx [{ id: 3, name: "Deno", description: "The fastest dinosaur that ever lived." }]; ``` -------------------------------- ### Define API routes with Oak and Prisma Source: https://github.com/denoland/examples/blob/main/with-prisma/readme.md Implementation of the main application logic, including Prisma client initialization and Oak router setup for CRUD operations. ```ts import { PrismaClient } from "./generated/client/deno/edge.ts"; import { Application, Router } from "https://deno.land/x/oak@v11.1.0/mod.ts"; import { config } from "https://deno.land/std@0.163.0/dotenv/mod.ts"; const envVars = await config(); /** * Initialize. */ const prisma = new PrismaClient({ datasources: { db: { url: envVars.DATABASE_URL, }, }, }); const app = new Application(); const router = new Router(); /** * Setup routes. */ router .get("/", (context) => { context.response.body = "Welcome to the Dinosaur API!"; }) .get("/dinosaur", async (context) => { // Get all dinosaurs. const dinosaurs = await prisma.dinosaur.findMany(); context.response.body = dinosaurs; }) .get("/dinosaur/:id", async (context) => { // Get one dinosaur by id. const { id } = context.params; const dinosaur = await prisma.dinosaur.findUnique({ where: { id: Number(id), }, }); context.response.body = dinosaur; }) .post("/dinosaur", async (context) => { // Create a new dinosaur. const { name, description } = await context.request.body("json").value; const result = await prisma.dinosaur.create({ data: { name, description, }, }); context.response.body = result; }) .delete("/dinosaur/:id", async (context) => { // Delete a dinosaur by id. const { id } = context.params; const dinosaur = await prisma.dinosaur.delete({ where: { id: Number(id), }, }); context.response.body = dinosaur; }); /** * Setup middleware. */ app.use(router.routes()); app.use(router.allowedMethods()); /** * Start server. */ await app.listen({ port: 8000 }); ``` -------------------------------- ### GitHub Actions Workflow for AWS Lightsail Source: https://github.com/denoland/examples/blob/main/on-aws-lightsail/readme.md A complete YAML workflow to build a Docker image, install the AWS CLI and lightsailctl, and deploy the container to AWS. ```yml name: Build and Deploy to AWS Lightsail on: push: branches: - main env: AWS_REGION: us-west-2 AWS_LIGHTSAIL_SERVICE_NAME: container-service-2 jobs: build_and_deploy: name: Build and Deploy runs-on: ubuntu-latest steps: - name: Checkout main uses: actions/checkout@v2 - name: Install Utilities run: | sudo apt-get update sudo apt-get install -y jq unzip - name: Install AWS Client run: | curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" unzip awscliv2.zip sudo ./aws/install || true aws --version curl "https://s3.us-west-2.amazonaws.com/lightsailctl/latest/linux-amd64/lightsailctl" -o "lightsailctl" sudo mv "lightsailctl" "/usr/local/bin/lightsailctl" sudo chmod +x /usr/local/bin/lightsailctl - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 with: aws-region: ${{ env.AWS_REGION }} aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} - name: Build Docker Image run: docker build -t ${{ env.AWS_LIGHTSAIL_SERVICE_NAME }}:release . - name: Push and Deploy run: | service_name=${{ env.AWS_LIGHTSAIL_SERVICE_NAME }} aws lightsail push-container-image \ --region ${{ env.AWS_REGION }} \ --service-name ${service_name} \ --label ${service_name} \ --image ${service_name}:release aws lightsail get-container-images --service-name ${service_name} | jq --raw-output ".containerImages[0].image" > image.txt jq --arg image $(cat image.txt) '.containers.app.image = $image' container.template.json > container.json aws lightsail create-container-service-deployment --service-name ${service_name} --cli-input-json file://$(pwd)/container.json ``` -------------------------------- ### GET /users/:id Source: https://github.com/denoland/examples/blob/main/with-oak-deno-kv/readme.md Retrieves a specific user by their ID. ```APIDOC ## GET /users/:id ### Description Retrieves a user by their unique ID. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user ``` -------------------------------- ### Dinosaur list JSON response Source: https://github.com/denoland/examples/blob/main/with-fastify/readme.md Example of the JSON array returned by the /api endpoint. ```json [ { "name": "Aardonyx", "description": "An early stage in the evolution of sauropods." }, { "name": "Abelisaurus", "description": "\"Abel's lizard\" has been reconstructed from a single skull." }, { "name": "Abrictosaurus", "description": "An early relative of Heterodontosaurus." }, ... ``` -------------------------------- ### GET /users/:id/address Source: https://github.com/denoland/examples/blob/main/with-oak-deno-kv/readme.md Retrieves the address associated with a specific user ID. ```APIDOC ## GET /users/:id/address ### Description Retrieves the address for a given user ID. ### Method GET ### Endpoint /users/:id/address ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user ``` -------------------------------- ### Single dinosaur JSON response Source: https://github.com/denoland/examples/blob/main/with-fastify/readme.md Example of the JSON object returned by the /api/:dinosaur endpoint. ```json { "name": "Aardonyx", "description": "An early stage in the evolution of sauropods." } ``` -------------------------------- ### Initialize project directory Source: https://github.com/denoland/examples/blob/main/with-prisma/readme.md Create and enter the project directory. ```shell mkdir rest-api-with-prisma-oak cd rest-api-with-prisma-oak ``` -------------------------------- ### Initialize project files Source: https://github.com/denoland/examples/blob/main/with-apollo/README.md Create the necessary files for the Apollo server implementation. ```bash touch schema.ts resolvers.ts main.ts ``` -------------------------------- ### Create Store File Source: https://github.com/denoland/examples/blob/main/with-vue/README.md Initialize the store file for state management. ```bash touch src/store.js ``` -------------------------------- ### Initialize API directory and files Source: https://github.com/denoland/examples/blob/main/with-react/readme.md Create the necessary directory structure and files for the backend API. ```sh mkdir api && touch api/data.json && touch api/main.ts ``` -------------------------------- ### Initialize Deno server Source: https://github.com/denoland/examples/blob/main/with-redis/README.md Sets up a basic Deno server to proxy requests to the GitHub API. ```typescript const server = new Server({ handler: async (req) => { const { pathname } = new URL(req.url); // strip the leading slash const username = pathname.substring(1); const resp = await fetch(`https://api.github.com/users/${username}`); const user = await resp.json(); return new Response(JSON.stringify(user), { headers: { "content-type": "application/json", }, }); } }, port: 3000, }); server.listenAndServe(); ``` -------------------------------- ### Initialize Prisma Source: https://github.com/denoland/examples/blob/main/with-prisma/readme.md Run the Prisma initialization command using Deno. ```shell deno run --allow-read --allow-env --allow-write npm:prisma@^4.5.0 init ``` -------------------------------- ### Create main.ts file Source: https://github.com/denoland/examples/blob/main/with-fastify/readme.md Command to initialize the main entry point file. ```bash touch main.ts ``` -------------------------------- ### Create Component Files Source: https://github.com/denoland/examples/blob/main/with-vue/README.md Initialize the necessary Vue component files in the src/components directory. ```bash touch src/components/HomePage.vue src/components/Dinosaurs.vue src/components/Dinosaur.vue ``` -------------------------------- ### Run Deno application Source: https://github.com/denoland/examples/blob/main/with-planetscale/README.md Execute the application with necessary network and environment permissions. ```shell deno run --allow-net --allow-env main.ts ``` -------------------------------- ### Scaffold a React project with Vite Source: https://github.com/denoland/examples/blob/main/with-react/readme.md Use the Vite CLI to initialize a new Deno-compatible React project. ```sh deno run -A npm:create-vite-extra ``` -------------------------------- ### Create Router Directory Source: https://github.com/denoland/examples/blob/main/with-vue/README.md Command to initialize the router directory and index file. ```bash mkdir router && touch router/index.ts ``` -------------------------------- ### Run the server Source: https://github.com/denoland/examples/blob/main/with-apollo/README.md Execute the server with required permissions. ```ts deno run --allow-net --allow-read --allow-env main.ts ``` -------------------------------- ### Run the Deno application Source: https://github.com/denoland/examples/blob/main/with-grafana/readme.md Executes the application using the defined Deno task. Requires a populated .env file with an OpenAI API key. ```bash $ deno task otel ``` -------------------------------- ### Run Deno server Source: https://github.com/denoland/examples/blob/main/with-redis/README.md Command to execute the Deno server with network permissions. ```bash deno run --allow-net main.ts ``` -------------------------------- ### Run Deno server Source: https://github.com/denoland/examples/blob/main/with-fastify/readme.md Command to execute the server script with necessary permissions. ```bash deno run -A main.ts ``` -------------------------------- ### Generate Deployment Configuration File Source: https://github.com/denoland/examples/blob/main/on-aws-lightsail/readme.md Command to inject the dynamic image URI into the template file using jq. ```bash jq --arg image $(cat image.txt) '.containers.app.image = $image' container.template.json > container.json ``` -------------------------------- ### Build, Tag, and Push Docker Image Source: https://github.com/denoland/examples/blob/main/on-digital-ocean/readme.md Builds the image from the local configuration, applies the required registry tag, and pushes it to the Digital Ocean Container Registry. ```bash docker compose -f docker-compose.yml build docker tag deno-image registry.digitalocean.com/deno-on-digital-ocean/deno-image:new docker push registry.digitalocean.com/deno-on-digital-ocean/deno-image:new ``` -------------------------------- ### Create seed file Source: https://github.com/denoland/examples/blob/main/with-prisma/readme.md Initialize the seed script file in the prisma directory. ```shell touch prisma/seed.ts ``` -------------------------------- ### Connecting to MySQL Source: https://github.com/denoland/examples/blob/main/with-mysql2/README.md Establish a connection to the MySQL server using createConnection with host, user, and password credentials. ```tsx const connection = await mysql.createConnection({ host: "localhost", user: "root", password: "password", }); ``` -------------------------------- ### Configure environment variables Source: https://github.com/denoland/examples/blob/main/with-planetscale/README.md Set database credentials as environment variables for secure access. ```bash export HOST= export USERNAME= export PASSWORD= ``` -------------------------------- ### Creating and Selecting Database Source: https://github.com/denoland/examples/blob/main/with-mysql2/README.md Execute SQL commands to create a new database and select it for subsequent operations. ```tsx await connection.query("CREATE DATABASE denos"); await connection.query("use denos"); ``` -------------------------------- ### Create data.json file Source: https://github.com/denoland/examples/blob/main/with-fastify/readme.md Command to create the data storage file. ```bash touch data.json ``` -------------------------------- ### Initialize database connection Source: https://github.com/denoland/examples/blob/main/with-planetscale/README.md Create a connection object using credentials retrieved from environment variables. ```tsx const config = { host: Deno.env.get("HOST"), username: Deno.env.get("USERNAME"), password: Deno.env.get("PASSWORD"), }; const conn = connect(config); ``` -------------------------------- ### POST /users/ Source: https://github.com/denoland/examples/blob/main/with-oak-deno-kv/readme.md Adds or updates a new user in the system. ```APIDOC ## POST /users/ ### Description Adds or updates (upserting) a new user. ### Method POST ### Endpoint /users/ ### Request Body - **id** (string) - Required - User identifier - **email** (string) - Required - User email address - **name** (string) - Required - User name - **password** (string) - Required - User password ### Request Example { "id": "1", "email": "andy@deno.com", "name": "andy", "password": "12345" } ``` -------------------------------- ### Create Digital Ocean Registry Source: https://github.com/denoland/examples/blob/main/on-digital-ocean/readme.md Initializes a new private container registry on Digital Ocean using the doctl CLI. ```bash doctl registry create deno-on-digital-ocean ``` -------------------------------- ### Define Container Deployment Configuration Source: https://github.com/denoland/examples/blob/main/on-aws-lightsail/readme.md Create a template file to define container environment variables, port mappings, and health check parameters. ```json { "containers": { "app": { "image": "", "environment": { "APP_ENV": "release" }, "ports": { "8000": "HTTP" } } }, "publicEndpoint": { "containerName": "app", "containerPort": 8000, "healthCheck": { "healthyThreshold": 2, "unhealthyThreshold": 2, "timeoutSeconds": 5, "intervalSeconds": 10, "path": "/", "successCodes": "200-499" } } } ``` -------------------------------- ### Build, Tag, and Push Docker Image Source: https://github.com/denoland/examples/blob/main/on-aws-lightsail/readme.md Commands to build the container image from a compose file, tag it for a specific Docker Hub repository, and push the image to the registry. ```bash docker compose -f docker-compose.yml build docker tag deno-image {{ username }}/deno-on-aws-lightsail docker push {{ username }}/deno-on-aws-lightsail ``` -------------------------------- ### Create pages directory Source: https://github.com/denoland/examples/blob/main/with-react/readme.md Use shell commands to create the pages directory and the necessary component files. ```sh mkdir src/pages && touch src/pages/Index.jsx src/pages/Dinosaur.jsx ``` -------------------------------- ### Create a Deno HTTP server Source: https://github.com/denoland/examples/blob/main/on-google-cloud-run/readme.md A basic Oak application that listens on port 8000. ```ts import { Application } from "https://deno.land/x/oak/mod.ts"; const app = new Application(); app.use((ctx) => { ctx.response.body = "Hello from Deno and Google Cloud Run!"; }); await app.listen({ port: 8000 }); ``` -------------------------------- ### Connect to Redis client Source: https://github.com/denoland/examples/blob/main/with-redis/README.md Initializes and connects to a local Redis instance. ```typescript // make a connection to the local instance of redis const client = createClient({ url: "redis://localhost:6379", }); await client.connect(); ``` -------------------------------- ### Generate Prisma client Source: https://github.com/denoland/examples/blob/main/with-prisma/readme.md Generate the Prisma client for Data Proxy. ```shell deno run -A npm:prisma generate --data-proxy ``` -------------------------------- ### Run seed script Source: https://github.com/denoland/examples/blob/main/with-prisma/readme.md Execute the seed script using Deno with full permissions. ```shell deno run -A prisma/seed.ts ``` -------------------------------- ### Define Dockerfile for Deno Source: https://github.com/denoland/examples/blob/main/on-digital-ocean/readme.md Configures the Docker image using the official Deno base image, caches dependencies, and sets the startup command. ```Dockerfile FROM denoland/deno EXPOSE 8000 WORKDIR /app ADD . /app RUN deno cache main.ts CMD ["run", "--allow-net", "main.ts"] ``` -------------------------------- ### Implement HomePage Component Source: https://github.com/denoland/examples/blob/main/with-vue/README.md Use Suspense to manage asynchronous loading of the Dinosaurs component. ```vue ``` -------------------------------- ### Create and populate table Source: https://github.com/denoland/examples/blob/main/with-planetscale/README.md Use the execute method to run SQL commands for table creation and data insertion. ```tsx await conn.execute( "CREATE TABLE dinosaurs (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, name varchar(255) NOT NULL, description varchar(255) NOT NULL);", ); await conn.execute( "INSERT INTO `dinosaurs` (id, name, description) VALUES (1, 'Aardonyx', 'An early stage in the evolution of sauropods.'), (2, 'Abelisaurus', 'Abels lizard has been reconstructed from a single skull.'), (3, 'Deno', 'The fastest dinosaur that ever lived.')", ); ``` -------------------------------- ### Deploy service via gcloud CLI Source: https://github.com/denoland/examples/blob/main/on-google-cloud-run/readme.md Deploy the containerized image to a Google Cloud Run service. ```shell gcloud run deploy hello-from-deno --image=us-central1-docker.pkg.dev/deno-app-368305/deno-repository/deno-cloudrun-image --region=us-central1 --allow-unauthenticated ``` -------------------------------- ### Import PlanetScale driver Source: https://github.com/denoland/examples/blob/main/with-planetscale/README.md Import the connect method from the @planetscale/database package. ```tsx import { connect } from "npm:@planetscale/database@^1.4"; ``` -------------------------------- ### Import Redis and Deno Server modules Source: https://github.com/denoland/examples/blob/main/with-redis/README.md Imports the necessary Deno HTTP server and Redis client modules. ```typescript import { Server } from "https://deno.land/std@0.148.0/http/server.ts"; import { createClient } from "npm:redis@^4.5"; ``` -------------------------------- ### Create Deno HTTP Application Source: https://github.com/denoland/examples/blob/main/on-digital-ocean/readme.md A basic Oak-based web server that listens on port 8000. ```ts import { Application } from "https://deno.land/x/oak/mod.ts"; const app = new Application(); app.use((ctx) => { ctx.response.body = "Hello from Deno and Digital Ocean!"; }); await app.listen({ port: 8000 }); ``` -------------------------------- ### Push database schema Source: https://github.com/denoland/examples/blob/main/with-prisma/readme.md Apply the schema changes to the database. ```shell deno run -A npm:prisma db push ``` -------------------------------- ### Build Docker Image Command Source: https://github.com/denoland/examples/blob/main/on-aws-lightsail/readme.md Command to build the local Docker image with a specific tag. ```bash docker build -t ${{ env.AWS_LIGHTSAIL_SERVICE_NAME }}:release . ``` -------------------------------- ### Implement Index page Source: https://github.com/denoland/examples/blob/main/with-react/readme.md Create the Index component to fetch and display a list of dinosaurs from the API. ```jsx import React, { useEffect, useState } from "react"; import { Link, useParams } from "react-router-dom"; const Index = () => { const [dinos, setDinos] = useState([]); useEffect(() => { fetch(`http://localhost:8000/api/`) .then(async (res) => await res.json()) .then((json) => setDinos(json)); }, []); return (

Welcome to the Dinosaur app

Click on a dinosaur below to learn more.

{dinos.map((dino) => { return (
{dino.name}
); })}
); }; export default Index; ``` -------------------------------- ### Define Docker configuration Source: https://github.com/denoland/examples/blob/main/on-google-cloud-run/readme.md Configuration files required to containerize the Deno application. ```Dockerfile FROM denoland/deno EXPOSE 8000 WORKDIR /app ADD . /app RUN deno cache main.ts CMD ["run", "--allow-net", "main.ts"] ``` ```yml version: '3' services: web: build: . container_name: deno-container image: deno-image ports: - "8000:8000" ``` -------------------------------- ### GitHub Actions Workflow Configuration Source: https://github.com/denoland/examples/blob/main/on-digital-ocean/readme.md A YAML workflow file that automates building, tagging, pushing a Docker image to the DigitalOcean Registry, and deploying it via SSH. ```yaml name: Deploy to Digital Ocean on: push: branches: - main env: REGISTRY: "registry.digitalocean.com/deno-on-digital-ocean" IMAGE_NAME: "deno-image" jobs: build_and_push: name: Build, Push, and Deploy runs-on: ubuntu-latest steps: - name: Checkout main uses: actions/checkout@v2 - name: Set $TAG from shortened sha run: echo "TAG=`echo ${GITHUB_SHA} | cut -c1-8`" >> $GITHUB_ENV - name: Build container image run: docker compose -f docker-compose.yml build - name: Tag container image run: docker tag ${{ env.IMAGE_NAME }} ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.TAG }} - name: Install `doctl` uses: digitalocean/action-doctl@v2 with: token: ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }} - name: Log in to Digital Ocean Container Registry run: doctl registry login --expiry-seconds 600 - name: Push image to Digital Ocean Container Registry run: docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.TAG }} - name: Deploy via SSH uses: appleboy/ssh-action@master with: host: ${{ secrets.DIGITALOCEAN_HOST }} username: ${{ secrets.DIGITALOCEAN_USERNAME }} key: ${{ secrets.DIGITALOCEAN_SSHKEY }} script: | # Login to Digital Ocean Container Registry docker login -u ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }} -p ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }} registry.digitalocean.com # Stop and remove a running image. docker stop ${{ env.IMAGE_NAME }} docker rm ${{ env.IMAGE_NAME }} # Run a new container from a new image docker run -d --restart always -it -p 8000:8000 --name ${{ env.IMAGE_NAME }} ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.TAG }} ``` -------------------------------- ### Test SSH Connection Source: https://github.com/denoland/examples/blob/main/on-digital-ocean/readme.md Verifies that the SSH key authentication is configured correctly. ```bash ssh -i ~/.ssh/mykey {{ username }}@{{ host }} ``` -------------------------------- ### Manage Docker images with gcloud Source: https://github.com/denoland/examples/blob/main/on-google-cloud-run/readme.md Commands to authenticate, build, tag, and push Docker images to Google Artifact Registry. ```shell gcloud auth configure-docker us-central1-docker.pkg.dev ``` ```shell docker compose -f docker-compose.yml build ``` ```shell docker tag deno-image us-central1-docker.pkg.dev/deno-app-368305/deno-repository/deno-cloudrun-image ``` ```shell docker push us-central1-docker.pkg.dev/deno-app-368305/deno-repository/deno-cloudrun-image ``` -------------------------------- ### Connect to MongoDB Source: https://github.com/denoland/examples/blob/main/with-mongoose/README.md Establishes a connection to a local MongoDB instance using Mongoose. ```ts import mongoose from "npm:mongoose@^6.7"; import Dinosaur from "./model/Dinosaur.ts"; await mongoose.connect("mongodb://localhost:27017"); // Check to see connection status. console.log(mongoose.connection.readyState); ``` -------------------------------- ### Run the OpenTelemetry collector Source: https://github.com/denoland/examples/blob/main/with-grafana/readme.md Builds and runs the OTel collector service in a Docker container, exposing ports 4317 and 4318. ```bash $ docker build -t otel-collector . && docker run -p 4317:4317 -p 4318:4318 otel-collector ``` -------------------------------- ### Importing mysql2 Source: https://github.com/denoland/examples/blob/main/with-mysql2/README.md Import the mysql2 promise wrapper using the npm specifier. ```tsx import mysql from "npm:mysql2@^2.3.3/promise"; ``` -------------------------------- ### Creating a Table Source: https://github.com/denoland/examples/blob/main/with-mysql2/README.md Define a new table structure using standard SQL syntax. ```tsx await connection.query( "CREATE TABLE `dinosaurs` ( `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` varchar(255) NOT NULL, `description` varchar(255) )", ); ``` -------------------------------- ### GitHub Actions Workflow for Cloud Run Deployment Source: https://github.com/denoland/examples/blob/main/on-google-cloud-run/readme.md A YAML workflow configuration that authenticates with GCP, builds a Docker image, pushes it to Google Artifact Registry, and deploys it to Cloud Run. ```yaml name: Build and Deploy to Cloud Run on: push: branches: - main env: PROJECT_ID: {{ PROJECT_ID }} GAR_LOCATION: {{ GAR_LOCATION }} REPOSITORY: {{ GAR_REPOSITORY }} SERVICE: {{ SERVICE }} REGION: {{ REGION }} jobs: deploy: name: Deploy permissions: contents: 'read' id-token: 'write' runs-on: ubuntu-latest steps: - name: CHeckout uses: actions/checkout@v3 - name: Google Auth id: auth uses: 'google-github-actions/auth@v0' with: credentials_json: '${{ secrets.GCP_CREDENTIALS }}' - name: Login to GAR uses: docker/login-action@v2.1.0 with: registry: ${{ env.GAR_LOCATION }}-docker.pkg.dev username: _json_key password: ${{ secrets.GCP_CREDENTIALS }} - name: Build and Push Container run: |- docker build -t "${{ env.GAR_LOCATION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.SERVICE }}:${{ github.sha }}" ./ docker push "${{ env.GAR_LOCATION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.SERVICE }}:${{ github.sha }}" - name: Deploy to Cloud Run id: deploy uses: google-github-actions/deploy-cloudrun@v0 with: service: ${{ env.SERVICE }} region: ${{ env.REGION }} image: ${{ env.GAR_LOCATION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.SERVICE }}:${{ github.sha }} - name: Show Output run: echo ${{ steps.deploy.outputs.url }} ``` -------------------------------- ### Define docker-compose.yml Source: https://github.com/denoland/examples/blob/main/on-digital-ocean/readme.md Orchestrates the container build and port mapping for local testing. ```yml version: '3' services: web: build: . container_name: deno-container image: deno-image ports: - "8000:8000" ``` -------------------------------- ### Deploy container service to AWS Lightsail Source: https://github.com/denoland/examples/blob/main/on-aws-lightsail/readme.md Executes a deployment to a specified Lightsail container service using a local JSON configuration file. ```bash aws lightsail create-container-service-deployment --service-name ${service_name} --cli-input-json file://$(pwd)/container.json ``` -------------------------------- ### Retrieve Container Image Information Source: https://github.com/denoland/examples/blob/main/on-aws-lightsail/readme.md Command to fetch the latest image URI from Lightsail and save it to a file. ```bash aws lightsail get-container-images --service-name ${service_name} | jq --raw-output ".containerImages[0].image" > image.txt ``` -------------------------------- ### Implement Dinosaur detail page Source: https://github.com/denoland/examples/blob/main/with-react/readme.md Create the Dinosaur component to fetch and display specific dinosaur details based on the URL parameter. ```jsx import React, { useEffect, useState } from "react"; import { Link, useParams } from "react-router-dom"; const Dinosaur = () => { const { dinosaur } = useParams(); const [dino, setDino] = useState({}); useEffect(() => { fetch(`http://localhost:8000/api/${dinosaur}`) .then(async (res) => await res.json()) .then((json) => setDino(json)); }, []); return (

{dino.name}

{dino.description}

See all
); }; export default Dinosaur; ``` -------------------------------- ### Update App Component Source: https://github.com/denoland/examples/blob/main/with-vue/README.md Configure the main application entry point to use the router view. ```vue ``` -------------------------------- ### Register Router in Main Entry Source: https://github.com/denoland/examples/blob/main/with-vue/README.md Import and use the router instance within the main application entry point. ```ts import { createApp } from "vue"; import "./style.css"; import App from "./App.vue"; import router from "./router/index.ts"; const app = createApp(App); app.use(router); app.mount("#app"); ``` -------------------------------- ### Implement the Oak backend API Source: https://github.com/denoland/examples/blob/main/with-react/readme.md Define routes and middleware for the dinosaur API server using Oak and CORS. ```ts import { Application, Router } from "https://deno.land/x/oak/mod.ts"; import { oakCors } from "https://deno.land/x/cors/mod.ts"; import data from "./data.json" with { type: "json" }; const router = new Router(); router .get("/", (context) => { context.response.body = "Welcome to dinosaur API!"; }) .get("/api", (context) => { context.response.body = data; }) .get("/api/:dinosaur", (context) => { if (context?.params?.dinosaur) { const filtered = data.filter((item) => item["name"].toLowerCase() === context.params.dinosaur.toLowerCase() ); if (filtered.length === 0) { context.response.body = "No dinosaurs found."; } else { context.response.body = filtered[0]; } } }); const app = new Application(); app.use(oakCors()); // Enable CORS for All Routes app.use(router.routes()); app.use(router.allowedMethods()); await app.listen({ port: 8000 }); ``` -------------------------------- ### Inserting Data Source: https://github.com/denoland/examples/blob/main/with-mysql2/README.md Populate the table with initial records using an INSERT statement. ```tsx await connection.query( "INSERT INTO `dinosaurs` (id, name, description) VALUES (1, 'Aardonyx', 'An early stage in the evolution of sauropods.'), (2, 'Abelisaurus', 'Abels lizard has been reconstructed from a single skull.'), (3, 'Deno', 'The fastest dinosaur that ever lived.')", ); ``` -------------------------------- ### Server response output Source: https://github.com/denoland/examples/blob/main/with-fastify/readme.md Expected output when accessing the root endpoint. ```text Welcome to the Dinosaur API! ``` -------------------------------- ### Define API routes Source: https://github.com/denoland/examples/blob/main/with-fastify/readme.md Adding routes to serve the imported dinosaur data. ```typescript fastify.get("/", (_req: FastifyRequest, reply: FastifyReply) => { reply.send("Welcome to the Dinosaur API!"); }); fastify.get("/api", (_req: FastifyRequest, reply: FastifyReply) => { reply.send(data); }); fastify.get( "/api/:dinosaur", ( req: FastifyRequest<{ Params: { dinosaur: string } }>, reply: FastifyReply, ) => { if (req.params.dinosaur) { const found = data.find((dino: { name: string; description: string; }) => dino.name.toLowerCase() === req.params.dinosaur?.toLowerCase()); if (found) { return reply.send(found); } } return reply.status(404).send({ message: "Dinosaur not found" }); }, ); await fastify.listen({ port: 8000 }); ``` -------------------------------- ### Test POST endpoint with curl Source: https://github.com/denoland/examples/blob/main/with-prisma/readme.md Command to send a JSON payload to the dinosaur creation endpoint. ```shell curl -X POST http://localhost:8000/dinosaur -H "Content-Type: application/json" -d '{"name": "Deno", "description":"The fastest, most secure, easiest to use Dinosaur ever to walk the Earth."}' ``` -------------------------------- ### Configure App routing Source: https://github.com/denoland/examples/blob/main/with-react/readme.md Define the application routes using BrowserRouter, Routes, and Route components in App.jsx. ```jsx import React from "react"; import { BrowserRouter as Router, Navigate, Route, Routes, } from "react-router-dom"; import Index from "./pages/Index.jsx"; import Dinosaur from "./pages/Dinosaur.jsx"; export default function App(props) { return ( } /> } /> } /> ); } ``` -------------------------------- ### Define seed script Source: https://github.com/denoland/examples/blob/main/with-prisma/readme.md Implementation of the database seeding logic using Prisma Client for Deno edge. ```ts import { Prisma, PrismaClient } from "../generated/client/deno/edge.ts"; import { config } from "https://deno.land/std@0.163.0/dotenv/mod.ts"; const envVars = await config(); const prisma = new PrismaClient({ datasources: { db: { url: envVars.DATABASE_URL, }, }, }); const dinosaurData: Prisma.DinosaurCreateInput[] = [ { name: "Aardonyx", description: "An early stage in the evolution of sauropods.", }, { name: "Abelisaurus", description: "Abel's lizard has been reconstructed from a single skull.", }, { name: "Acanthopholis", description: "No, it's not a city in Greece.", }, ]; /** * Seed the database. */ for (const u of dinosaurData) { const dinosaur = await prisma.dinosaur.create({ data: u, }); console.log(`Created dinosaur with id: ${dinosaur.id}`); } console.log(`Seeding finished.`); await prisma.$disconnect(); ``` -------------------------------- ### Querying All Data Source: https://github.com/denoland/examples/blob/main/with-mysql2/README.md Retrieve all records from the dinosaurs table and log the results. ```tsx const results = await connection.query("SELECT * FROM `dinosaurs`"); console.log(results); ``` -------------------------------- ### Push Container Image Command Source: https://github.com/denoland/examples/blob/main/on-aws-lightsail/readme.md Command to push the local Docker image to the Lightsail container service. ```bash aws lightsail push-container-image ... ``` -------------------------------- ### Configure Prisma schema Source: https://github.com/denoland/examples/blob/main/with-prisma/readme.md Define the generator, datasource, and data models in the schema file. ```ts generator client { provider = "prisma-client-js" previewFeatures = ["deno"] output = "../generated/client" } datasource db { provider = "postgresql" url = env("DATABASE_URL") } model Dinosaur { id Int @id @default(autoincrement()) name String @unique description String } ``` -------------------------------- ### Generate SSH Key Pair Source: https://github.com/denoland/examples/blob/main/on-digital-ocean/readme.md Creates a new SSH key pair on the local machine for authentication. ```bash ssh-keygen ``` -------------------------------- ### Define Vue Routes Source: https://github.com/denoland/examples/blob/main/with-vue/README.md Configure route paths and components in router/index.ts. ```ts import { createRouter, createWebHistory } from "vue-router"; import HomePage from "../components/HomePage.vue"; import Dinosaur from "../components/Dinosaur.vue"; const routes = [ { path: "/", name: "Home", component: HomePage, }, { path: "/:dinosaur", name: "Dinosaur", component: Dinosaur, props: true, }, ]; const router = createRouter({ history: createWebHistory("/"), routes, }); export default router; ``` -------------------------------- ### Upload Public SSH Key to Droplet Source: https://github.com/denoland/examples/blob/main/on-digital-ocean/readme.md Copies the local public key to the remote Droplet's authorized_keys file to enable passwordless SSH access. ```bash ssh-copy-id {{ username }}@{{ host }} ``` ```bash ssh-copy-id -i ~/.ssh/mykey {{ username }}@{{ host }} ``` -------------------------------- ### Add Instance Method to Schema Source: https://github.com/denoland/examples/blob/main/with-mongoose/README.md Extends the Dinosaur schema with a custom instance method for updating descriptions. ```ts // ./model/Dinosaur.ts // Methods. dinosaurSchema.methods = { // Update description. updateDescription: async function (description: string) { this.description = description; return await this.save(); }, }; // ... ``` -------------------------------- ### Configure Vite for Vue Router Source: https://github.com/denoland/examples/blob/main/with-vue/README.md Import vue-router in the vite.config.mjs file to ensure the dependency is available. ```ts import { defineConfig } from "npm:vite@^3.1.3"; import vue from "npm:@vitejs/plugin-vue@^3.2.39"; import "npm:vue@^3.2.39"; import "npm:vue-router@4"; // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], }); ``` -------------------------------- ### Retrieve a user by email Source: https://github.com/denoland/examples/blob/main/with-oak-deno-kv/readme.md Fetch a specific user record using their email address. ```http GET /users/email/:email ``` ```bash curl https://localhost:8000/users/email/andy@deno.com ``` -------------------------------- ### Implement resolvers Source: https://github.com/denoland/examples/blob/main/with-apollo/README.md Define the logic to populate data fields in resolvers.ts. ```tsx const dinosaurs = [ { name: "Aardonyx", description: "An early stage in the evolution of sauropods.", }, { name: "Abelisaurus", description: '"Abel\'s lizard" has been reconstructed from a single skull.', }, ]; export const resolvers = { Query: { dinosaurs: () => dinosaurs, dinosaur: (_: any, args: any) => { return dinosaurs.find((dinosaur) => dinosaur.name === args.name); }, }, }; ``` -------------------------------- ### Add react-router-dom dependency Source: https://github.com/denoland/examples/blob/main/with-react/readme.md Include react-router-dom in the vite.config.mjs file to enable routing capabilities. ```mjs import { defineConfig } from "npm:vite@^3.1.3"; import react from "npm:@vitejs/plugin-react@^2.1"; import "npm:react@^18.2"; import "npm:react-dom/client@^18.2"; import "npm:react-router-dom@^6.4"; // Add this line // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], }); ``` -------------------------------- ### Implement Dinosaur Component Source: https://github.com/denoland/examples/blob/main/with-vue/README.md Display individual dinosaur details retrieved from the reactive store. ```vue ``` -------------------------------- ### Manipulate Data in MongoDB Source: https://github.com/denoland/examples/blob/main/with-mongoose/README.md Demonstrates creating, finding, and updating documents using the Dinosaur model. ```ts // main.ts // Create a new Dinosaur. const deno = new Dinosaur({ name: "Deno", description: "The fastest dinosaur ever lived.", }); // // Insert deno. await deno.save(); // Find Deno by name. const denoFromMongoDb = await Dinosaur.findOne({ name: "Deno" }); console.log( `Finding Deno in MongoDB -- \n ${denoFromMongoDb.name}: ${denoFromMongoDb.description}`, ); // Update description for Deno and save it. await denoFromMongoDb.updateDescription( "The fastest and most secure dinosaur ever lived.", ); // Check MongoDB to see Deno's updated description. const newDenoFromMongoDb = await Dinosaur.findOne({ name: "Deno" }); console.log( `Finding Deno (again) -- \n ${newDenoFromMongoDb.name}: ${newDenoFromMongoDb.description}`, ); ``` -------------------------------- ### Implement Dinosaurs Component Source: https://github.com/denoland/examples/blob/main/with-vue/README.md Fetch dinosaur data from an API and render links that update the global store. ```vue ``` -------------------------------- ### Upsert a new user Source: https://github.com/denoland/examples/blob/main/with-oak-deno-kv/readme.md Send a POST request to /users/ to add or update a user record. ```json { "id": "1", "email": "andy@deno.com", "name": "andy", "password": "12345" } ``` ```bash curl -X POST http://localhost:8000/users -H "Content-Type: application/json" -d '{ "id": "1", "email": "andy@deno.com", "name": "andy", "password": "12345" }' ``` -------------------------------- ### Query database records Source: https://github.com/denoland/examples/blob/main/with-planetscale/README.md Retrieve all rows from the dinosaurs table and log the results. ```tsx const results = await conn.execute("SELECT * FROM `dinosaurs`"); console.log(results.rows); ``` -------------------------------- ### Define Reactive Store Source: https://github.com/denoland/examples/blob/main/with-vue/README.md Define a reactive store to share dinosaur data across components. ```javascript import { reactive } from "vue"; export const store = reactive({ dinosaur: {}, setDinosaur(name, description) { this.dinosaur.name = name; this.dinosaur.description = description; }, }); ``` -------------------------------- ### Add an address to a user Source: https://github.com/denoland/examples/blob/main/with-oak-deno-kv/readme.md Send a POST request to /users/:id/address to associate an address with a user. ```http POST /users/:id/address ``` ```json { "city": "los angeles", "street": "main street" } ``` ```bash curl -X POST http://localhost:8000/users/1/address -H "Content-Type: application/json" -d '{ "city": "los angeles", "street": "main street" }' ``` -------------------------------- ### Retrieve a user by ID Source: https://github.com/denoland/examples/blob/main/with-oak-deno-kv/readme.md Fetch a specific user record using their unique ID. ```http GET /users/:id ``` ```bash curl https://localhost:8000/users/1 ``` -------------------------------- ### POST /users/:id/address Source: https://github.com/denoland/examples/blob/main/with-oak-deno-kv/readme.md Adds an address to a specific user. ```APIDOC ## POST /users/:id/address ### Description Adds an address to a user identified by the provided ID. ### Method POST ### Endpoint /users/:id/address ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user ### Request Body - **city** (string) - Required - City name - **street** (string) - Required - Street name ### Request Example { "city": "los angeles", "street": "main street" } ```