U-w*_*ays 6 javascript scalar schema graphql graphql-js
我正在以编程方式构建 GraphQL 架构,并且需要Timestamp标量类型;Unix 纪元时间戳标量类型:
const TimelineType = new GraphQLObjectType({
name: 'TimelineType',
fields: () => ({
date: { type: new GraphQLNonNull(GraphQLTimestamp) },
price: { type: new GraphQLNonNull(GraphQLFloat) },
sold: { type: new GraphQLNonNull(GraphQLInt) }
})
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,GraphQL.js没有aGraphQLTimestamp也没有 aGraphQLDate类型,所以上面的方法不起作用。
我期待一个Date输入,我想将其转换为时间戳。我将如何创建自己的 GraphQL 时间戳类型?
有一个 NPM 包,其中包含一组符合 RFC 3339 的日期/时间 GraphQL 标量类型;graphql-iso-date。
但对于初学者来说,您应该以GraphQLScalarType编程方式在 GraphQL 中构建自己的标量类型:
/** Kind is an enum that describes the different kinds of AST nodes. */
import { Kind } from 'graphql/language';
import { GraphQLScalarType } from 'graphql';
const TimestampType = new GraphQLScalarType({
name: 'Timestamp',
serialize(date) {
return (date instanceof Date) ? date.getTime() : null
},
parseValue(date) {
try { return new Date(value); }
catch (error) { return null; }
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return new Date(parseInt(ast.value, 10));
}
else if (ast.kind === Kind.STRING) {
return this.parseValue(ast.value);
}
else {
return null;
}
},
});
Run Code Online (Sandbox Code Playgroud)
但这个问题( #550 )并没有重新发明轮子,而是已经被讨论过,并且 Pavel Lang 提出了一个不错的GraphQLTimestamp.js解决方案(我的TimestampType解决方案源自他的)。
| 归档时间: |
|
| 查看次数: |
15067 次 |
| 最近记录: |