NodeJS/GraphQL:尝试使用自定义 DateTime 标量时出现错误
NodeJS/GraphQL: Trying to use a custom DateTime scalar and I'm getting an error
我正在学习一个教程,其中老师正在为他的 createdAt
字段使用 String
类型,并建议如果我们愿意,可以使用自定义标量类型来获得更强类型的 DateTime
字段,所以我正在尝试这样做。
我收到以下错误:Error: Unknown type "GraphQLDateTime".
这是有问题的代码:
const { gql } = require('apollo-server')
const { GraphQLDateTime } = require('graphql-iso-date')
module.exports = gql`
type Post {
id: ID!
username: String!
body: String!
createdAt: GraphQLDateTime!
}
type User {
id: ID!
email: String!
token: String!
username: String!
createdAt: GraphQLDateTime!
}
input RegisterInput {
username: String!
password: String!
confirmPassword: String!
email: String!
}
type Query {
getPosts: [Post]
getPost(postId: ID!): Post
}
type Mutation {
register(registerInput: RegisterInput): User
login(username: String!, password: String!): User!
createPost(body: String!): Post!
deletePost(postId: ID!): String!
}
`
我已经添加了 graphql-iso-date
库,VSCode 的智能感知正在接收它,所以我知道这不是问题所在。这也表明 GraphQLDateTime
没有在文件中的任何地方使用,即使我正在引用它。
我知道这可能是一个简单的修复,但我对 NodeJS 上下文中的 NodeJS 和 GraphQL 仍然是新手。知道我做错了什么吗?还有另一个 DateTime 标量可能更可取(最佳实践总是一个好主意。)谢谢!
使用 apollo-server
或 graphql-tools
添加自定义标量有两个步骤:
将标量定义添加到您的类型定义中:
scalar DateTime
将实际的 GraphQLScalar 添加到解析器映射:
const { GraphQLDateTime } = require('graphql-iso-date')
const resolvers = {
/* your other resolvers */
DateTime: GraphQLDateTime,
}
请注意,解析器映射中的键(我在这里使用 DateTime
)必须与您在步骤 1 中用作标量名称的任何名称相匹配。这也将是您在类型定义中使用的名称。名称本身是任意的,但需要匹配。
有关详细信息,请参阅 the docs。
我正在学习一个教程,其中老师正在为他的 createdAt
字段使用 String
类型,并建议如果我们愿意,可以使用自定义标量类型来获得更强类型的 DateTime
字段,所以我正在尝试这样做。
我收到以下错误:Error: Unknown type "GraphQLDateTime".
这是有问题的代码:
const { gql } = require('apollo-server')
const { GraphQLDateTime } = require('graphql-iso-date')
module.exports = gql`
type Post {
id: ID!
username: String!
body: String!
createdAt: GraphQLDateTime!
}
type User {
id: ID!
email: String!
token: String!
username: String!
createdAt: GraphQLDateTime!
}
input RegisterInput {
username: String!
password: String!
confirmPassword: String!
email: String!
}
type Query {
getPosts: [Post]
getPost(postId: ID!): Post
}
type Mutation {
register(registerInput: RegisterInput): User
login(username: String!, password: String!): User!
createPost(body: String!): Post!
deletePost(postId: ID!): String!
}
`
我已经添加了 graphql-iso-date
库,VSCode 的智能感知正在接收它,所以我知道这不是问题所在。这也表明 GraphQLDateTime
没有在文件中的任何地方使用,即使我正在引用它。
我知道这可能是一个简单的修复,但我对 NodeJS 上下文中的 NodeJS 和 GraphQL 仍然是新手。知道我做错了什么吗?还有另一个 DateTime 标量可能更可取(最佳实践总是一个好主意。)谢谢!
使用 apollo-server
或 graphql-tools
添加自定义标量有两个步骤:
将标量定义添加到您的类型定义中:
scalar DateTime
将实际的 GraphQLScalar 添加到解析器映射:
const { GraphQLDateTime } = require('graphql-iso-date') const resolvers = { /* your other resolvers */ DateTime: GraphQLDateTime, }
请注意,解析器映射中的键(我在这里使用 DateTime
)必须与您在步骤 1 中用作标量名称的任何名称相匹配。这也将是您在类型定义中使用的名称。名称本身是任意的,但需要匹配。
有关详细信息,请参阅 the docs。