我在nodejs 中设置了apollo graphql 服务器。下面是源代码。我可以启动服务器,它开始侦听端口 6000。但是This site can\xe2\x80\x99t be reached当我在浏览器中打开 url ( http://localhost:6000/graphiql) 时,我得到了。我想知道我的代码有什么问题。
const express = require(\'express\');\nconst bodyParser = require(\'body-parser\');\nconst { graphqlExpress, graphiqlExpress } = require(\'apollo-server-express\');\nconst { makeExecutableSchema } = require(\'graphql-tools\');\n\n// Some fake data\nconst books = [\n {\n title: "Harry Potter and the Sorcerer\'s stone",\n author: \'J.K. Rowling\',\n },\n {\n title: \'Jurassic Park\',\n author: \'Michael Crichton\',\n },\n];\n\n// The GraphQL schema in string form\nconst typeDefs = `\n type Query { books: [Book] }\n type Book { title: …Run Code Online (Sandbox Code Playgroud) 我是一个初学者,尝试使用 apollo-express 和 prisma 设置 graphql API
一切都很顺利,但我决定使用这个库来添加输入验证: graphql-constraint-directive
它要求我使用 makeExecutableSchema 来构建我的架构,以便我可以使用schemaDirectives参数
我启动服务器的代码是这样的:
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({req}) => {
const userId = getUserID(req);
return {
userId,
prisma
}
}
});
Run Code Online (Sandbox Code Playgroud)
一切都很顺利
但为了使用该库,我将其重构如下:
const schema = makeExecutableSchema({
typeDefs,
resolvers,
schemaDirectives: {constraint: ConstraintDirective}
});
const server = new ApolloServer({
schema,
context: ({req}) => {
const userId = getUserID(req);
return {
userId,
prisma
}
}
});
Run Code Online (Sandbox Code Playgroud)
它也有效,我所有的查询和突变都有效,验证也有效。
但它破坏了 graphql-playground:它不再能够加载我的架构和文档,两个选项卡都是空的。它显示以下错误: 无法访问服务器
它仍然有效:我能够发送我的查询和突变等,但我不再有代码完成和自动文档,因为它知道我的模式,因此不再有用
如果我替换纯 typeDefs 和解析器的可执行模式,那么它会再次正常工作,playground 会再次加载所有内容
使用 …
我按照Apollo Docs 教程使用 TypeScript 构建 Apollo Server (Express),并且还使用GraphQL 代码生成器根据我的 GraphQL 架构生成必要的类型。
这是我当前的codegen.json配置:
{
"schema": "./lib/schema/index.graphql",
"generates": {
"./dist/typings/graphql/schema.d.ts": {
"plugins": [
"typescript",
"typescript-resolvers"
],
"config": {
"typesPrefix": "GQL",
"skipTypename": true,
"noSchemaStitching": true,
"useIndexSignature": true
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我当前基于教程的 GraphQL 模式(它并不完整,我还没有完成整个事情,我已经修剪了一些东西以使示例更小):
type Query {
launch(id: ID!): Launch
}
type Launch {
id: ID!
site: String
mission: Mission
}
enum PatchSize {
SMALL
LARGE
}
type Mission {
name: String
missionPatch(mission: String, size: PatchSize): String …Run Code Online (Sandbox Code Playgroud) 使用文档中的简单“电影 API”示例。我在函数ttl中添加了 a getMovie,以便将结果缓存 10 分钟。如何使updateMovie函数中的缓存失效?
const { RESTDataSource } = require('apollo-datasource-rest');
class MoviesAPI extends RESTDataSource {
async getMovie(id) {
return this.get(`movies/${id}`, {}, { cacheOptions: { ttl: 600 } });
}
async updateMovie(id, data) {
const movie = await this.put(`movies/${id}`, data);
// invalidate cache here?!
return movie;
}
}
Run Code Online (Sandbox Code Playgroud)
我知道KeyValueCache传递给 ApolloServer 的接口提供了一个delete函数。但是,该对象似乎没有在数据源中公开。它被包装在 内部HTTPCache,仅公开一个fetch函数。也KeyValueCache被包装在 a 内PrefixingKeyValueCache,因此假设RESTDataSource.
我正在尝试使用 GraphQL(Apollo 服务器)查询单个 MongoDB 文档 ( trivia),但其中一个文档字段遇到问题。
LightningRoundQuestion.answer并且PictureRoundPicture.answer应该返回一个String,并且MultipleChoiceRoundQuestion.answer应该返回一个Int。查看架构:
schema
const typeDefs = gql`
# ROOT TYPES ==================================================
type Query {
trivia(_id: String!): Trivia
}
# INTERFACES ==================================================
interface Round {
type: String!
theme: String!
pointValue: Int!
}
type LightningRound implements Round {
type: String!
theme: String!
pointValue: Int!
questions: [LightningRoundQuestion]
}
type MultipleChoiceRound implements Round {
type: String!
theme: String!
pointValue: Int!
questions: [MultipleChoiceRoundQuestion]
}
type PictureRound implements Round { …Run Code Online (Sandbox Code Playgroud) 我一直在努力弄清楚如何让文件上传在 graphql 中工作。
\n这是我的基本实现。
\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nconst { ApolloServer, gql } = require(\'apollo-server-express\')\n// eslint-disable-next-line import/no-extraneous-dependencies\nconst express = require(\'express\')\n\n\nconst typeDefs = gql` \n type File {\n filename: String!\n mimetype: String!\n encoding: String!\n }\n \n type Query {\n _ : Boolean\n }\n \n type Mutation {\n singleUpload(file: Upload!): File!,\n singleUploadStream(file: Upload!): File!\n }\n`;\n\nconst resolvers = {\n Mutation: {\n singleUpload: (parent, args) => {\n return args.file.then(file => {\n const {createReadStream, filename, mimetype} = file\n\n const fileStream = createReadStream()\n\n return file;\n });\n …Run Code Online (Sandbox Code Playgroud) 将身份验证添加到后端 Graphql 服务器后,“Schema”和“Docs”在 Graphql Playground 中不再可见。在 Playground 中向“HTTP HEADERS”添加令牌时执行查询在经过身份验证时可以正常工作,而在用户未经身份验证时则不能正常工作,所以没关系。
我们禁用了 Apollo 服务器的内置 Playground,并使用中间件graphql-playground-middleware-express来使用不同的 URL 并绕过身份验证。我们现在可以浏览到 Playground 并使用它,但我们无法读取那里的“架构”或“文档”。
尝试启用introspection并没有解决此问题。passport.authenticate()打电话过来会更好Context吗apollo-server?还有一个名为Passport-graphql 的工具,但它适用于本地策略,可能无法解决问题。我还尝试在调用 Playground 路由之前在标头中设置令牌,但这不起作用。
我们对此有点迷失。感谢您为我们提供的任何见解。
相关代码:
// index/ts
import passport from 'passport'
import expressPlayground from 'graphql-playground-middleware-express'
const app = express()
app.use(cors({ origin: true }))
app.get('/playground', expressPlayground({ endpoint: '/graphql' }))
app.use(passport.initialize())
passport.use(bearerStrategy)
app.use(
passport.authenticate('oauth-bearer', { session: false }),
(req, _res, next) => { next() }
)
;(async () => { …Run Code Online (Sandbox Code Playgroud) 因此,我通过在 Next.js 上实现 Apollo 客户端来研究 GraphQL,我从未实现过 GraphQL API 或使用过 Apollo,并且在构建和操作查询时遇到了一些问题。我想使用 SpaceX GraphQL 服务器创建一些静态页面,并使用 getStaticProps 和 getStaticPath 从 SpaceX 服务器获取前 10 个结果,从这些路由创建静态页面并获取每个 id 的发射详细信息。我的问题是,我无法使启动详细信息查询工作。服务器响应 400。由于结构正确,问题一定是在将变量传递给查询时出现的。
再说一遍,我从未实现过 Apollo 客户端,并且对 graphQL 有非常初级的了解,并且无法找到使用文档的问题。我的代码基于此示例,我刚刚删除了 useQuery Hook,以便我可以在 getStaticProps 内发出请求。 https://www.apollographql.com/docs/react/data/queries/
// [launchId].tsx
import { initializeApollo } from '../../lib/ApolloClient'
export const getStaticPaths: GetStaticPaths = async () => {
const apolloClient = initializeApollo()
const {
data: { launchesPast }
} = await apolloClient.query({
query: gql`
{
launchesPast(limit: 10) {
id
}
}
`
})
const paths = launchesPast.map(element …Run Code Online (Sandbox Code Playgroud) 我试图将文件上传到我的 apollo 服务器,但我无法上传任何文件,也不会引发任何错误,但我在解析器中只收到空对象,当我使用像Altair 这样的GraphQL客户端时,它可以正常工作
使用 Altair 客户端时在服务器中输出
{
filename: 'Copy of Massive Orange Summer Sale Animated-300x250px-MediumRectangle.png',
mimetype: 'image/png',
encoding: '7bit',
createReadStream: [Function: createReadStream]
}
Run Code Online (Sandbox Code Playgroud)
使用 @apollo/client 包时服务器中的输出
{}
Run Code Online (Sandbox Code Playgroud)
客户代码

服务器代码

graphql-js buildSchema和apollo-server 有什么区别gql?他们似乎做着非常相似的工作。
apollo-server ×10
graphql ×7
apollo ×3
graphql-js ×3
react-apollo ×2
caching ×1
express ×1
graphql-tag ×1
javascript ×1
node.js ×1
passport.js ×1
prisma ×1
reactjs ×1
typescript ×1