文档中心

探索 DWeb 框架的无限可能,构建下一代高性能 Web 应用

GraphQL

DWeb 框架提供了 GraphQL 服务器支持,可以轻松构建 GraphQL API。

快速开始

基本使用

Code
import { GraphQLServer } from "@dreamer/dweb";
import { Server } from "@dreamer/dweb";

// 定义 GraphQL Schema
const typeDefs = `
  type Query {
    hello: String
    user(id: ID!): User
  }

  type User {
    id: ID!
    name: String!
    email: String!
  }
`;

// 定义 Resolvers
const resolvers = {
  Query: {
    hello: () => "Hello World",
    user: (parent, args) => {
      return {
        id: args.id,
        name: "John Doe",
        email: "[email protected]",
      };
    },
  },
};

// 创建 GraphQL 服务器
const graphqlServer = new GraphQLServer({
  typeDefs,
  resolvers,
});

// 在 HTTP 服务器中使用
const server = new Server();
server.setHandler(async (req, res) => {
  if (req.url.startsWith("/graphql")) {
    return await graphqlServer.handleRequest(req, res);
  }
  res.text("Not Found", 404);
});

await server.start(3000);

在路由中使用

Code
// routes/api/graphql.ts
import { GraphQLServer } from "@dreamer/dweb";
import type { ApiContext } from "@dreamer/dweb";

const graphqlServer = new GraphQLServer({
  typeDefs: `
    type Query {
      hello: String
    }
  `,
  resolvers: {
    Query: {
      hello: () => "Hello from GraphQL",
    },
  },
});

export async function post({ req, res }: ApiContext) {
  return await graphqlServer.handleRequest(req, res);
}

使用数据源

在 GraphQL Resolver 中使用数据库:

Code
import { GraphQLServer } from "@dreamer/dweb";
import { getDatabase } from "@dreamer/dweb";

const graphqlServer = new GraphQLServer({
  typeDefs: `
    type Query {
      users: [User!]!
    }
    type User {
      id: ID!
      name: String!
      email: String!
    }
  `,
  resolvers: {
    Query: {
      users: async () => {
        const db = await getDatabase();
        return await db.query("SELECT * FROM users");
      },
    },
  },
});

订阅支持

GraphQL 服务器支持订阅(Subscriptions)功能,可以实现实时数据推送:

Code
import { GraphQLServer } from "@dreamer/dweb";

const graphqlServer = new GraphQLServer({
  typeDefs: `
    type Query {
      hello: String
    }
    type Subscription {
      messageAdded: Message
    }
    type Message {
      id: ID!
      content: String!
    }
  `,
  resolvers: {
    Query: {
      hello: () => "Hello",
    },
    Subscription: {
      messageAdded: {
        subscribe: () => {
          // 返回 AsyncIterator
          return messagePubSub.asyncIterator("MESSAGE_ADDED");
        },
      },
    },
  },
});

API 参考

GraphQLServer

Code
new GraphQLServer(config: GraphQLServerConfig)
Code
interface GraphQLServerConfig {
  typeDefs: string;
  resolvers: Resolvers;
  context?: (req: Request) => any;
  formatError?: (error: GraphQLError) => any;
}

方法

  • handleRequest(req, res) - 处理 GraphQL 请求
  • executeQuery(query, variables?, context?) - 执行 GraphQL 查询

相关文档