Gar*_*ett 7 apollo graphql react-apollo apollo-client
使用以下 graphql:
scalar Date
type MyModel {
id: ID!
date: Date!
}
query MyModels {
myModels {
id
date
}
}
type Query {
myModel: [MyModel!]
}
Run Code Online (Sandbox Code Playgroud)
和解析器:
import { DateTimeResolver } from 'graphql-scalars'
const resolvers = {
// Scalars
Date: DateTimeResolver,
myModels: async () => {
return await context.user.getMyModels()
}
}
Run Code Online (Sandbox Code Playgroud)
我的查询返回date: "2021-02-07T06:58:51.009Z". 是否可以让 Apollo Client 将其转换为 Date 对象?
使用apollo-link-scalars解决了这个问题:
import {
ApolloClient,
InMemoryCache,
HttpLink,
ApolloLink,
} from '@apollo/client'
import introspectionResult from 'shared/gql/generated.schema.json'
import { buildClientSchema, IntrospectionQuery } from 'graphql'
import { withScalars } from 'apollo-link-scalars'
import { DateTimeResolver } from 'graphql-scalars'
const schema = buildClientSchema(
(introspectionResult as unknown) as IntrospectionQuery
)
const httpLink = new HttpLink({
uri: 'http://localhost:4000',
credentials: 'include',
})
const typesMap = {
DateTime: DateTimeResolver,
}
const link = ApolloLink.from([
(withScalars({ schema, typesMap }) as unknown) as ApolloLink,
httpLink,
])
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link,
// TODO: Save and hydrate from localStorage
cache: new InMemoryCache(),
// Necessary to pass the session cookie to the server on every request
credentials: 'include',
})
}
Run Code Online (Sandbox Code Playgroud)
我查看了生成的模式,发现标量被调用,DateTime而不是Date所以我将其更改typeMap为DateTime: DateTimeResolver并且它正在工作。
| 归档时间: |
|
| 查看次数: |
4586 次 |
| 最近记录: |