惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Hacker News: Front Page
博客园 - 【当耐特】
量子位
博客园 - 聂微东
H
Hackread – Cybersecurity News, Data Breaches, AI and More
The Register - Security
The Register - Security
Last Week in AI
Last Week in AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Tailwind CSS Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
雷峰网
雷峰网
Blog — PlanetScale
Blog — PlanetScale
P
Proofpoint News Feed
Jina AI
Jina AI
The Cloudflare Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
AWS News Blog
AWS News Blog
L
LINUX DO - 最新话题
酷 壳 – CoolShell
酷 壳 – CoolShell
The GitHub Blog
The GitHub Blog
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
Security @ Cisco Blogs
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Schneier on Security
Stack Overflow Blog
Stack Overflow Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Engineering at Meta
Engineering at Meta
W
WeLiveSecurity
博客园 - 三生石上(FineUI控件)
Security Archives - TechRepublic
Security Archives - TechRepublic
Hugging Face - Blog
Hugging Face - Blog
T
Troy Hunt's Blog
C
CERT Recently Published Vulnerability Notes
N
News and Events Feed by Topic
S
SegmentFault 最新的问题
美团技术团队
C
CXSECURITY Database RSS Feed - CXSecurity.com
人人都是产品经理
人人都是产品经理
SecWiki News
SecWiki News
N
News and Events Feed by Topic
C
Check Point Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
宝玉的分享
宝玉的分享
Schneier on Security
Schneier on Security
阮一峰的网络日志
阮一峰的网络日志
Cisco Talos Blog
Cisco Talos Blog
T
Threat Research - Cisco Blogs
J
Java Code Geeks

Deno

Deno 2.8 | Deno Claw Patrol: an open-source security firewall for agents | Deno Fresh 2.3: Zero JS by default, View Transitions, and Temporal support | Deno Deno 2.7: Temporal API, Windows ARM, and npm overrides | Deno Build a dinosaur runner game with Deno, pt. 6 | Deno Build a dinosaur runner game with Deno, pt. 5 | Deno Deno Deploy is Generally Available | Deno Introducing Deno Sandbox | Deno Build a dinosaur runner game with Deno, pt. 4 | Deno Build a dinosaur runner game with Deno, pt. 3 | Deno Build a dinosaur runner game with Deno, pt. 2 | Deno React / Next.js Denial-of-Service Vulnerability: Deno Deploy users protected | Deno Deno 2.6: dx is the new npx | Deno Build a dinosaur runner game with Deno, pt. 1 | Deno React Server Functions / Next.js Vulnerability: Deno Deploy users protected | Deno My highlights from the new Deno Deploy | Deno Deno's Other Open Source Projects | Deno How Deno protects against npm exploits | Deno Help Us Raise $200k to Free JavaScript from Oracle | Deno Deno 2.5: Permissions in the config file | Deno Fresh 2.0 Graduates to Beta, Adds Vite Support | Deno Deno 2.4: deno bundle is back | Deno JavaScript™ Trademark Update | Deno What's coming to JavaScript | Deno A brief history of JavaScript | Deno Reports of Deno's Demise Have Been Greatly Exaggerated | Deno An Update on Fresh | Deno How Plaid migrated 100 services to a new database platform 5x faster with Deno | Deno Deno 2.3: Improved deno compile, local npm packages, and more | Deno Add JSR packages with pnpm and Yarn | Deno Zero-config Debugging with Deno and OpenTelemetry | Deno Exploring Art with TypeScript, Jupyter, Polars, and Observable Plot | Deno Deno v Oracle Update 3: Fighting the JavaScript Trademark | Deno Build a custom RAG AI agent in TypeScript and Jupyter | Deno How to get deep traces in your Node.js backend with OTel and Deno | Deno toranoana.deno #20 登録受付中(2025年3月14日) | Deno Node just added TypeScript support. What does that mean for Deno? | Deno The Dino 🦕, the Llama 🦙, and the Whale 🐋 | Deno Publish a lint rule, get a prize | Deno Deno 2.2: OpenTelemetry, Lint Plugins, node:sqlite | Deno If you're not using npm specifiers, you're doing it wrong | Deno How Deno's documentation is evolving | Deno Oracle justified its JavaScript trademark with Node.js—now it wants that ignored | Deno Introducing the JSR open governance board | Deno Intro to Wasm in Deno | Deno Announcing OpenAI on JSR | Deno Deno in 2024 | Deno Goodbye WinterCG, welcome WinterTC | Deno Build a SolidJS app with Deno | Deno Run your Next.js SSR app on Deno Deploy | Deno Solve Advent of Code 2024 with Deno and Win Prizes! | Deno Deno v. Oracle: Canceling the JavaScript Trademark | Deno Deno 2.1: Wasm Imports and other enhancements | Deno Build a Typesafe API with tRPC and Deno | Deno Self-contained Executable Programs with Deno Compile | Deno Build a Database App with Drizzle ORM and Deno | Deno Introducing your new JavaScript package manager: Deno | Deno Announcing Growthbook on JSR | Deno Build an Astro site with Deno | Deno How to convert CommonJS to ESM | Deno Announcing Deno 2 | Deno The Final Touches: What’s New In v2.0.0-rc.10 | Deno Announcing Stable V8 Bindings for Rust | Deno Deno 2.0 Release Candidate | Deno Secure, efficient private npm registries with Cloudsmith and Deno | Deno Painting the Plane as We Fly It: Designing JSR | Deno Introducing Web Cache API support on Deno Deploy | Deno Deno 1.46: The Last 1.x Release | Deno Protect your cloud spend with new Deno Deploy spend limits | Deno What we got wrong about HTTP imports | Deno Benchmarking AWS Lambda Cold Starts Across JavaScript Runtimes | Deno Announcing Supabase on JSR | Deno Deno 1.45: Workspace and Monorepo Support | Deno Introducing KV Backup for Deno Subhosting | Deno A Gentle Intro to TypeScript | Deno Announcing Hono on JSR | Deno How We Made the Deno Language Server Ten Times Faster | Deno How the Guardian uses Deno to audit accessibility and performance across their 2.7 million articles | Deno Introducing More Flexible Domain Association for Deno Subhosting | Deno The stabilization process of the Standard Library has begun | Deno Deno 1.44: Private npm registries, improved Node.js compat, and performance boosts | Deno How we built a secure, performant, multi-tenant cloud platform to run untrusted code | Deno The Deno Standard Library is now available on JSR | Deno How to document your JavaScript package | Deno Your Low Code Solution Needs an Escape Hatch | Deno Deno 1.43: Improved Language Server performance | Deno How Slack used Deno to save months of engineering effort in launching their new platform | Deno JSR Is Not Another Package Manager | Deno Announcing the Hookdeck SDK on JSR | Deno Announcing the Neon Serverless Driver on JSR | Deno An intro to TSConfig for JavaScript Developers | Deno How we built JSR | Deno How Netlify used Deno Subhosting to build a successful edge functions product | Deno Introducing Simpler Project Creation in Deno Deploy | Deno Deno 1.42: Better dependency management with JSR | Deno Introducing deployctl, the command line interface for Deno Deploy | Deno Introducing JSR - the JavaScript Registry | Deno How to add Monaco to a Next.js app and securely run untrusted user code | Deno Survey Results and Roadmap | Deno Deno 1.41: smaller deno compile binaries | Deno
How to Build a GraphQL Server with Deno | Deno
Andy Jiang · 2023-01-11 · via Deno

GraphQL is a popular approach to building APIs, since it makes it easy for developers to access only the data they need, saving bandwidth and reducing waterfall requests, which leads to better client performance.

In this tutorial we’re going to show you how to build a GraphQL API server with Deno.

View source here.

You could also use Apollo with npm specifiers in this tutorial. Note, however, that npm specifiers are not yet available on Deno Deploy.

Hello, World!

Let’s set up a “Hello, World!” example of GraphQL with Deno.

We’ll create an empty file called hello_world_server.ts and add our dependencies.

import { Server } from "https://deno.land/std@0.166.0/http/server.ts";
import { GraphQLHTTP } from "https://deno.land/x/gql@1.1.2/mod.ts";
import { makeExecutableSchema } from "https://deno.land/x/graphql_tools@0.0.2/mod.ts";
import { gql } from "https://deno.land/x/graphql_tag@0.0.1/mod.ts";

We’ll see each of these in action below, but briefly:

  • Server constructs our HTTP server
  • GraphQLHTTP creates the GraphQL HTTP middleware using the schema we specify
  • makeExecutableSchema creates a schema based on our type definitions and resolvers
  • gql creates our type definitions

First, let’s setup the types and our resolver with gql:

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

Here our Query type has a field “hello” that is a String. Once we have the type, we need a resolver for that Query. Resolvers handle the functionality of Queries and Mutations.

In this case, all we want our Query to do is print “Hello, World!”

const resolvers = {
  Query: {
    hello: () => `Hello, World!`,
  },
};

To work with our server, we need to combine our types and resolvers into a schema. We can do that with makeExecutableSchema:

const schema = makeExecutableSchema({ resolvers, typeDefs });

The schema object will then be passed to GraphQLHTTP, which is inside our main HTTP server:

const server = new Server({
  handler: async (req) => {
    const { pathname } = new URL(req.url);

    return pathname === "/graphql"
      ? await GraphQLHTTP<Request>({
        schema,
        graphiql: true,
      })(req)
      : new Response("Not Found", { status: 404 });
  },
  port: 3000,
});

So the main wrapper is a new Server object. Within that we have a handler that handles the request from the browser. We get the url, and if it includes /graphql, we run the GraphQLHTTP middleware, passing in our schema and setting graphiql as true (you can also do this without graphiql, using either Postman/Insomnia or straight curl).

And if it’s not the /graphql page, return a 404 status and print out “Not found”.

The final line will start the server on the port we assigned (3000) and listen:

Run this with the --allow-net flag to make sure we have network access:

$ deno run --allow-net hello_world_server.ts

If we then go to localhost:3000/graphql we’ll see the graphiql interface:

Demo of the graphiql interface

Then you can run the query:

And receive the response:

{
  "data": {
    "hello": "Hello World!"
  }
}

And just like that, you are GraphQLing!

Hello, (Prehistoric) World!

All well and good, but what makes GraphQL APIs so powerful is interacting with data. Let’s expand our example so that we can query our data, choose what response we receive, and insert data into our database.

So let’s set up a backend database and load it with some data that we can query and add to.

For our data store, we’ll use Postgres (you can set up a Postgres instance on Supabase by following our tutorial here → Connecting to Postgres).

Next, let’s add some extremely important data to our database: dinosaurs.json.

With the exception of adding a mutation (which is how you add data in GraphQL), there is very little to change from our “Hello, World!” to get this working. But we are going to refactor our code to keep our project a little tidier.

First, we’ll create the a typedefs.ts file and move our types there, along with the gql import:

import { gql } from "https://deno.land/x/graphql_tag@0.0.1/mod.ts";

export const typeDefs = gql`
  type Query {
    allDinosaurs: [Dinosaur]
    oneDinosaur(name: String): Dinosaur
  }

  type Dinosaur {
    name: String
    description: String
  }

  type Mutation {
    addDinosaur(name: String, description: String): Dinosaur
  }
`;

We now have a few more types to define:

  • Our two Queries are allDinosaurs and OneDinosaur. allDinosaurs returns a list (denoted by the square brackets). OneDinosaur returns one Dinosaur.
  • Dinosaur is the object we return from our Queries, which contains a String name and description.
  • addDinosaur is our Mutation to add a Dinosaur with a name and description to our database.

We’ll also move our Query and Mutation resolvers out to resolvers.ts as these now contain more functionality. resolvers.ts is also where we’re going to connect to Postgres.

So we first need to import our Postgres library:

import * as postgres from "https://deno.land/x/postgres@v0.14.2/mod.ts";

Then we can build our connect function to Postgres:

const connect = async () => {
  
  const databaseUrl = Deno.env.get("DATABASE_URL")!;

  
  const pool = new postgres.Pool(databaseUrl, 3, true);

  
  const connection = await pool.connect();
  return connection;
};

We can access environment variables with Deno.env.get() (we’ll use the --allow-env flag to enable access to the environment variables for Postgres). Here, our DATABASE_URL is the stored Postgres connection string. Then, we create a pool of connections and connect to the database.

Then we can define our Query and Mutation functions. We’ll create two Query functions, one to get a list of all the dinosaurs in our database (allDinosaurs), and another to get just one by name (oneDinosaur):

const allDinosaurs = async () => {
  const connection = await connect();
  const result = await connection.queryObject`
          SELECT name, description FROM dinosaurs
        `;
  return result.rows;
};

const oneDinosaur = async (args: any) => {
  const connection = await connect();
  const result = await connection.queryObject`
          SELECT name, description FROM dinosaurs WHERE name = ${args.name}
        `;
  return result.rows;
};

allDinosaurs connects to the database and returns a list of all the Dinosaurs therein. oneDinosaur is similar but:

  1. it takes an argument, which will be the name of the Dinosaur we want
  2. it uses that argument name to query the database for just that Dinosaur

We also have a Mutation function to add a Dinosaur to the database:

const addDinosaur = async (args: any) => {
  const connection = await connect();
  const result = await connection.queryObject`
            INSERT INTO dinosaurs(name, description) VALUES(${args.name}, ${args.description}) RETURNING name, description
        `;
  return result.rows[0];
};

Once we have all the functions in place, we can reference them within our resolvers:

export const resolvers = {
  Query: {
    allDinosaurs: () => allDinosaurs(),
    oneDinosaur: (_: any, args: any) => oneDinosaur(args),
  },
  Mutation: {
    addDinosaur: (_: any, args: any) => addDinosaur(args),
  },
};

With the resolvers and type definitions out of the main file (which we’ll rename to server.ts), we need to import them into that file, but the rest of server.ts can remain the same:

import { Server } from "https://deno.land/std@0.166.0/http/server.ts";
import { GraphQLHTTP } from "https://deno.land/x/gql@1.1.2/mod.ts";
import { makeExecutableSchema } from "https://deno.land/x/graphql_tools@0.0.2/mod.ts";
import { resolvers } from "./resolvers.ts";
import { typeDefs } from "./typedefs.ts";

const schema = makeExecutableSchema({ resolvers, typeDefs });

const server = new Server({
  handler: async (req) => {
    const { pathname } = new URL(req.url);

    return pathname === "/graphql"
      ? await GraphQLHTTP<Request>({
        schema,
        graphiql: true,
      })(req)
      : new Response("Not Found", { status: 404 });
  },
  port: 3000,
});

server.listenAndServe();

When we run server.ts this time, we’ll also need the --allow-env flag to let Postgres work properly:

deno run --allow-net --allow-env server.ts

If we go to localhost:3000/graphql, we’ll see the graphiql interface like before, but this time, the autocomplete will have the options for our new Queries and Mutation, such as querying allDinosaurs:

query {
  allDinosaurs {
    name
    description
  }
}

This will generate a list of all the Dinosaurs in the database:

Query all dinosaurs.

Remember, one of the fly things about GraphQL is that the end user can choose what data they want to request. In this case, we could just choose to only retrieve names:

Query all dinosaurs, but only get the names.

We can also run the oneDinosaur Query to get just one dinosaur:

query {
  oneDinosaur(name:"Aardonyx") {
    name
    description
  }
}

Query a single dinosaur named Aardonyx

Finally, we can add a dinosaur with addDinosaur:

mutation {
  addDinosaur(name:"Deno",description:"the fastest Deno in the world") {
    name
    description
  }
}

We supply the name and description, but we can also ask for the name and description back from the API, to check that the Dinosaur was added:

Add Deno to database via mutation.

To be doubly sure, we can also use oneDinosaur again:

Query one dinosaur, Deno.

What’s next?

This server shows a basic implementation of GraphQL with Deno, but there is a ton more you can do like defining more types, queries, and relationships between your data. For example, here every dinosaur is independent, but we could add a Clade type to our definitions entries and show how Aardonyx is related to the Seitaad and the Sefapanosaurus.

We can also build out a frontend to use this data. To see what that looks like, check out our How to Build an E-commerce Site with a Perfect Lighthouse Score to see how we use the Shopify GraphQL API in our merch store.

Let us know on Twitter or on our Discord what else you want to learn to do with Deno.