使用TypeScript构建GraphQL API:逐步实践教程

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程
```html

使用 TypeScript 的 GraphQL API 简介



GraphQL 是一种用于 API 的查询语言,它允许客户端只请求他们真正需要的数据。与 TypeScript 结合使用时,您将获得严格的类型检查、IDE 中的自动补全以及编译阶段更少的错误。在本教程中,我们将使用 TypeScript 和 Apollo Server 从头开始构建一个完整的 GraphQL API。



本指南适合熟悉 JavaScript 和 Node.js 基础的开发者。我们将从安装依赖项到测试完成的 API 逐步进行。



1. 项目设置与依赖安装



首先,创建一个新项目并安装必要的包。打开终端并执行:



mkdir graphql-ts-tutorialcd graphql-ts-tutorialnpm init -y


安装 TypeScript、Apollo Server 和 GraphQL:



npm install apollo-server graphqlnpm install -D typescript @types/node ts-node nodemon


创建 tsconfig.json 文件用于 TypeScript 配置:



{  "compilerOptions": {    "target": "ES2020",    "module": "commonjs",    "rootDir": "./src",    "outDir": "./dist",    "strict": true,    "esModuleInterop": true,    "skipLibCheck": true  },  "include": ["src/**/*"]}


创建 src 文件夹和 src/index.ts 文件——这将是应用程序的入口点。



2. 创建 GraphQL 模式和 TypeScript 类型



在 GraphQL 中,模式定义了客户端可用的数据类型和操作。让我们创建一个简单的模式来管理书籍。



文件 src/schema.ts:



import { gql } from 'apollo-server';

export const typeDefs = gql` type Book { id: ID! title: String! author: String! publishedYear: Int }

type Query { books: [Book] book(id: ID!): Book }

type Mutation { addBook(title: String!, author: String!, publishedYear: Int): Book deleteBook(id: ID!): Book }`;


现在为我们的数据定义 TypeScript 接口。创建 src/types.ts:



export interface Book {  id: string;  title: string;  author: string;  publishedYear?: number;}


请注意:TypeScript 接口用于内部逻辑,而 GraphQL 类型用于客户端-服务器交互。它们应该保持一致。



3. 实现解析器和服务器



解析器是为模式中的每个字段返回数据的函数。让我们创建一个 src/resolvers.ts 文件,并模拟一个数据库:



import { Book } from './types';

let books: Book[] = [ { id: '1', title: '战争与和平', author: '列夫·托尔斯泰', publishedYear: 1869 }, { id: '2', title: '罪与罚', author: '费奥多尔·陀思妥耶夫斯基', publishedYear: 1866 },];

export const resolvers = { Query: { books: (): Book[] => books, book: (_: any, args: { id: string }): Book | undefined => { return books.find(book => book.id === args.id); }, }, Mutation: { addBook: (_: any, args: { title: string; author: string; publishedYear?: number }): Book => { const newBook: Book = { id: String(books.length + 1), title: args.title, author: args.author, publishedYear: args.publishedYear, }; books.push(newBook); return newBook; }, deleteBook: (_: any, args: { id: string }): Book | null => { const index = books.findIndex(book => book.id === args.id); if (index === -1) return null; const deletedBook = books.splice(index, 1)[0]; return deletedBook; }, },};


现在将所有内容连接到主文件 src/index.ts 中:



import { ApolloServer } from 'apollo-server';import { typeDefs } from './schema';import { r
```                

博客

书籍推荐