[英]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.