【第六天】搭建Web环境 – GraphQL模拟服务器

首先

スライド7.PNG

这是2023年圣诞节倒数日历的第六天。

 

在之前的基础上,我们将继续推进开发人员能够进行Web开发的话题。

image.png

阿波罗服务器

阿波羅伺服器是什么

    Apollo Serverは、GraphQL APIを構築するためのオープンソースのWebサーバーです

 

安装并启动

我希望使用 ApolloServer + TypeScript 进行启动。
(Wǒ ApolloServer + TypeScript .)

npm init --yes && npm pkg set type="module"
npm install @apollo/server graphql
npm install --save-dev typescript @types/node @graphql-tools/load
{
  "compilerOptions": {
    "rootDirs": ["src"],
    "outDir": "dist",
    "lib": ["es2020"],
    "target": "es2020",
    "module": "esnext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "types": ["node"]
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}
  "scripts": {
-   "test": "echo \"Error: no test specified\" && exit 1",
+   "compile": "tsc",
+   "start": "npm run compile && node ./dist/index.js"
  }

创建模式

我会设置Schema文件。

后来这里将由GraphQL Code Generator自动生成的代码来进行更改。
为了进行操作验证而安装在这里。
type Blog {
  author: String!
  body: String!
  createdAt: String!
  title: String!
}

type Query {
  blogs: [Blog!]!
}

创建Index.ts

创建用于启动服务器的TS文件。

import { ApolloServer } from '@apollo/server'
import { loadSchemaSync } from '@graphql-tools/load'
import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader'
import { startStandaloneServer } from '@apollo/server/standalone'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const schema = loadSchemaSync(join(__dirname, '../schema.graphql'), {
  loaders: [new GraphQLFileLoader()],
})

const resolvers = {
  Query: {
    blogs: () => [],
  },
}

const server = new ApolloServer({
  typeDefs: schema,
  resolvers,
})

const { url } = await startStandaloneServer(server, { listen: { port: 4000 } })

console.log(`? Server listening at: ${url}`)

让我们开始吧 ba)

让我们尝试启动。

npm run start
image.png

通过这个命令,模拟服务器已经启动了。

为了便于推进GraphQL开发,我们将进行GraphQL Code Generator的配置。

广告
将在 10 秒后关闭
bannerAds