[英]MongoDB, GraphQL and ISODate type
我有一个关于 MongoDB ISODate 类型和 GraphQL 的问题。 我需要声明一个mutation
在我的GQL的架构,允许在我蒙戈数据库中添加文件。
该文档具有 ISODate 属性,但在我的 gql 架构中,我使用的是String
:
mutation addSomething(data: SomeInput)
type SomeInput {
field1: String
field2: Int
created: String
}
我的问题是,在新文档中, created
字段是字符串格式(不是 ISODate),我期待着。 但我想知道如何使它插入一个 ISODate 。 我可以在某处使用“自定义类型”代替 String 吗?
谢谢
PS:我正在使用 nodeJS 和 apollo 库。
我发现这个包https://www.npmjs.com/package/graphql-iso-date增加了 3 个日期自定义类型。
这是我的 gql 架构:
const { gql } = require('apollo-server');
const { GraphQLDateTime } = require('graphql-iso-date')
const typeDefs = gql`
scalar GraphQLDateTime
type Resto {
restaurant_id: ID!
borough: String
cuisine: String
name: String
address: Address
grades: [Grade]
}
type Address {
building: String
street: String
zipcode: String
coord: [Float]
}
type Grade {
date: GraphQLDateTime
grade: String
score: Int
}
input GradeInput {
date: GraphQLDateTime
grade: String
score: Int
}
extend type Query {
GetRestos: [Resto]
GetRestoById(id: ID!): Resto
}
extend type Mutation {
UpdateGradeById(grade: GradeInput!, id: ID!): Resto
RemoveGradeByIdAndDate(date: String, id: ID!): Resto
}
`
module.exports = typeDefs;
这是基于 样本餐厅数据集的测试。
因此,如果我尝试像这样调用UpdateGradeById()
函数:
UpdateGradeById(grade:{date:"2020-08-25T08:00:00.000Z",grade:"D",score:15},id:"30075445"){...}
文档已更新,但日期始终为字符串格式(如下面的屏幕截图所示):
列表中最后一个成绩的日期被识别为字符串(而不是日期)。
我可以看到改进,因为在我使用graphql-iso-date
之前,日期字段以时间戳格式返回。 现在它们作为 ISO 字符串返回。 但是插入没有按预期工作。
好的,我错过了在我之前的例子中做一些重要的事情:解析器。 所以,如果你像我一样想通过 GraphQL 操作 MongoDB 日期类型,你可以像这样使用graphql-iso-date
包:
首先,通过添加新标量来修改您的架构:
const { gql } = require('apollo-server');
const typeDefs = gql`
scalar ISODate
type Resto {
restaurant_id: ID!
borough: String
cuisine: String
name: String
address: Address
grades: [Grade]
}
type Address {
building: String
street: String
zipcode: String
coord: [Float]
}
type Grade {
date: ISODate
grade: String
score: Int
}
input GradeInput {
date: ISODate
grade: String
score: Int
}
extend type Query {
GetRestos: [Resto]
GetRestoById(id: ID!): Resto
}
extend type Mutation {
UpdateGradeById(grade: GradeInput!, id: ID!): Resto
RemoveGradeByIdAndDate(date: ISODate!, id: ID!): Resto
}
`
module.exports = typeDefs;
(这里我选择调用我的自定义日期标量ISODate )
然后,您必须通过修改解析器文件来告诉如何“解析”这个新的 ISODate 标量:
const { GraphQLDateTime } = require('graphql-iso-date')
module.exports = {
Query: {
GetRestos: (_, __, { dataSources }) =>
dataSources.RestoAPI.getRestos(),
GetRestoById: (_, {id}, { dataSources }) =>
dataSources.RestoAPI.getRestoById(id),
},
Mutation: {
UpdateGradeById: (_, {grade,id}, { dataSources }) =>
dataSources.RestoAPI.updateGradeById(grade,id),
RemoveGradeByIdAndDate: (_, {date,id}, { dataSources }) =>
dataSources.RestoAPI.removeGradeByIdAndDate(date,id),
},
ISODate: GraphQLDateTime
};
就是这样。 现在,我的 mongodb 文档中的日期属性被很好地识别为日期类型值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.