我正在尝试在apollo服务器上定义自定义标量,到目前为止,这是我所拥有的
自定义标量文件(timestamp.js)
import { isRFC3339 } from 'validator';
import { GraphQLScalarType } from 'graphql';
export default new GraphQLScalarType({
name: 'Timestamp',
description: 'RFC3339 Timestamp format',
serialize(value) {
if (isRFC3339(value)) {
return value;
}
throw new Error('Timestamp cannot represent an invalid RFC-3339 Timestamp string');
},
parseValue(value) {
if (isRFC3339(value)) {
return value;
}
throw new Error('Timestamp cannot represent an invalid RFC-3339 Timestamp string');
},
parseLiteral(ast) {
if (isRFC3339(ast.value)) {
return ast.value;
}
throw new Error('Timestamp cannot represent an invalid RFC-3339 Timestamp string');
}
});
在我的模式中,我的模式位于多个文件中,但是在将它们传递给makeExecutableSchema之前,我将它们连接在一起。
scalar Timestamp
在具有makeExecutableSchema的文件上,该文件稍后导出,并且是我的服务器构造函数中的用户。
import timeStamp from './scalars/timeStamp';
.
.
.
.
const schema = {
typeDefs: [
myTypeDefs
],
resolvers: merge(
resolvers,
timeStamp
),
};
export default makeExecutableSchema({
typeDefs: schema.typeDefs,
resolvers: schema.resolvers
});
我不知道我错过了什么,因为尝试运行API时出现此错误
throw new _1.SchemaError("\"" + typeName + "\" defined in resolvers, but has invalid value \"" + resolverValue + "\". A resolver's value " +
^
Error: "name" defined in resolvers, but has invalid value "Timestamp". A resolver's value must be of type object or function.
任何帮助将不胜感激。预先感谢!
答案 0 :(得分:1)
使用apollo-server
(或graphql-tools
)构建模式时,resolvers
参数必须是其属性为
换句话说,生成的对象应类似于:
const resolvers = {
Query: {
// field resolvers here...
},
// Maybe some other object types here...
Timestamp: timeStamp,
}
请注意,对于我们的自定义标量,属性名称需要与我们为标量指定的名称匹配。这也是您在typeDefs
中包含的名称。在这种情况下,属性将为Timestamp
,我们将其设置为实例化的GraphQLScalarType
。
因此,假设您的实际resolvers
变量的格式正确,则需要执行以下操作:
merge(
resolvers,
{ Timestamp: timeStamp }
)
或者,您也可以更改timeStamp的默认导出...
export default { Timestamp: new GraphQLScalarType(...) }
或者只是完全放弃使用merge
,而使用了扩展语法:)
resolvers: {
...resolvers,
Timestamp: timeStamp,
}