我刚刚学习了如何使用graphql-yoga并prisma-binding基于HowToGraphQL 教程来创建 GraphlQL 服务器。
问题:目前查询数据库的唯一方法是使用通过运行命令启动的 Prisma Playground 网页graphql playground。
是否可以从 Node.js 脚本执行相同的查询?我遇到了 Apollo 客户端,但它似乎是为了从 React、Vue、Angular 等前端层使用。
我们正在研究一个相当复杂的 GraphQL 模式,其中我们有几个属于各种微服务的对象类型,其中每个对象类型都有一个我们可以查询的自然 API 端点。因此,如果可以直接为某些对象类型定义特定的解析器,则将非常方便,执行如下操作:
const typeDefs = gql`
type Query {
getBook(bookId: ID!): BookPayload
}
type BookPayload {
book: Book
userErrors: UserError
}
type Book {
id: ID!
title: String
author: String
}
`;
const resolvers = {
Query: {
getBook: (parent, args, context, info) => {
return {
book: { id: args.bookId }
}
},
Book: (parent) => { // this object type level resolver doesn't seem to work
return {
id: parent.id,
...fetchBookMetadata(parent.id)
};
}
};
Run Code Online (Sandbox Code Playgroud)
我知道这是一个微不足道的例子,可能看起来有点过度设计,但当模式开始变得非常复杂时,它确实更有意义(至少对我们而言),到处都是数百个交叉引用。现在有解决这个问题的好方法吗?
我正在Network Error {"type":"WriteError"}处理我的阿波罗查询。查询在到达客户端时执行得很好。但是在他的商店里写它有问题。任何想法可能会出错?这是查询:
fragment BpmnProcessInstanceItemTask on BpmnTaskInstance {
id
dateStarted
dateFinished
task {
name
__typename
}
performer {
name
__typename
}
performerRoles
__typename
}
fragment BpmnProcessInstanceItem on BpmnProcessInstance {
id
status
process {
name
description
type
__typename
}
owner {
name
__typename
}
tasks {
...BpmnProcessInstanceItemTask
__typename
}
dateStarted
dateFinished
__typename
}
query BpmnProcessInstancesQuery($input: BpmnProcessInstancesInput!) {
bpmnProcessInstancesQuery(input: $input) {
...BpmnProcessInstanceItem
__typename
}
}
Run Code Online (Sandbox Code Playgroud)
”
我的流星/反应/阿波罗(带提升)项目有问题。当我从服务器查询数据时,它会将 __typename 添加到我查询中的每个对象和子对象,但在我的情况下,它会产生一个主要问题,因为我通常会重用这些数据将它们发送到其他突变。现在另一个突变告诉我有一个错误,因为 __typename 字段没有在我的 graphql 模式中定义。
我试图通过将 addTypename: false 字段添加到我的 apollo 客户端来修复,但它没有改变任何东西(注意我正在使用 apollo boost,这可能是它不工作的原因):
const client = new ApolloClient({
uri: Meteor.absoluteUrl('graphql'),
addTypename: false,
request: operation =>
operation.setContext(() => ({
headers: {
authorization: Accounts._storedLoginToken()
}
}))
})
Run Code Online (Sandbox Code Playgroud)
此外,即使它有效,它似乎也不是很优化。在我看来,将字段添加到查询结果中似乎很成问题,我很惊讶没有在网上找到任何明确的解决方案。一些建议的解决方案,其中:
但它们似乎都不符合阿波罗假设为查询带来的“简单性”。我希望提供一个更简单、更合乎逻辑的解决方案,但到目前为止,找不到任何解决方案。
我有一个带有 GraphQL 的快速后端,当我去/graphiql手动执行一些搜索时它可以工作。我的 React 前端正在尝试在后端执行搜索。以下代码应异步执行查询:
const data = await this.props.client.query({
query: MY_QUERY,
variables: { initials: e.target.value }
});
console.log(data);
Run Code Online (Sandbox Code Playgroud)
WhereMY_QUERY是之前定义的,代表一个我知道有效并已在/graphiql. 在我做出反应组分I出口它这样做,因为export default withApollo(MyComponent)这样它具有client可变props。
在index.js我通过 Apollo 定义的文件中,连接到/graphiql以执行查询:
//link defined to deal with errors, this was found online
const link = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
); …Run Code Online (Sandbox Code Playgroud) 当我第一次使用 Apollo 为每次获取处理 GraphQl API 时,只有 Apollo 从服务器获取,其他总是从本地缓存获取
let apollo = ApolloClient(url: URL(string: graphQLEndpoint)!)
let meetingsQuery = AllMeetingsQuery()
apollo.fetch(query: meetingsQuery) { [weak self] result, error in
guard let meetings = result?.data?.allMeetings else { return }
print(conferences.count)
self?.conferences = conferences.map {$0.fragments.meetingDetails }
}
Run Code Online (Sandbox Code Playgroud) 我有一个简单的 GraphQL 枚举,定义如下:
enum PassType {
DailyFit
StarterFit
MonthlyFit
QuarterlyFit
DoubleFit
MultiFit10
MultiFit20
}
Run Code Online (Sandbox Code Playgroud)
我想在<select>标签中重用这些值。我使用 Apollo 和 AWS Appync 作为 GraphQL 基础设施。有没有办法从 Apollo 客户端获取这些,而无需在前端手动复制它们?
我正在尝试 Apollo 并使用以下相关代码:
const withQuery = graphql(gql`
query ApolloQuery {
apolloQuery {
data
}
}
`);
export default withQuery(props => {
const {
data: { refetch, loading, apolloQuery },
} = props;
return (
<p>
<Button
variant="contained"
color="primary"
onClick={async () => { await refetch(); }}
>
Refresh
</Button>
{loading ? 'Loading...' : apolloQuery.data}
</p>
);
});
Run Code Online (Sandbox Code Playgroud)
服务器延迟 500 毫秒,然后再发送{ data: `Hello ${new Date()}` }作为有效负载的响应。当我单击按钮时,我希望看到Loading...,但组件仍然会在Hello [date]半秒后显示并重新渲染。
根据此,在networkStatus应该是4( refetch),并且因此loading应该是真实的。我的期望错了吗?或者 …
我是 nodejs 和 apollo 服务器的新手,所以不要评判我。
问题听起来与标题完全相同:“如何在解析器函数中获取 graphql 字符串?”。
实际上,每个解析器中都有四个 args:parent、args、context、info。这里的一些信息:https : //www.apollographql.com/docs/apollo-server/essentials/data#type-signature
我决定编写函数,在上下文中收集嵌套对象以重新生成查询字符串。为什么我需要它?好问题。我正在编写微服务,所以当我将嵌套查询嵌套到当前微服务之外的字段时,我通过 http 传递查询。
我的解析器:
eventByID: async (root, args, context) => {
const event = await EventModel.findById(root.id);
event.creator = await nestedContextProvider(context, 'creator', event.creator);
return eventFascade(event); //just fascade for object - nothing serious
Run Code Online (Sandbox Code Playgroud)
},
它引用了nestedContextProvider 来解决嵌套上下文:
const nestedQueryTraverser = (nestedQueryArray) => {
const nestedQueryTraversed = nestedQueryArray.selectionSet.selections.map(element => (
element.selectionSet === undefined
? element.name.value
: `${element.name.value}{${nestedQueryTraverser(element)}}`));
return nestedQueryTraversed;
};
const nestedContextProvider = async (context, checkField, ID) => {
if (context.operation.selectionSet.selections[0].selectionSet.selections …Run Code Online (Sandbox Code Playgroud) 我的应用程序包含<Apollo />基本上初始化客户端的组件。
const client = new ApolloClient({
link: new HttpLink({
// ...
}),
cache: new InMemoryCache({
// ..
}),
});
Run Code Online (Sandbox Code Playgroud)
再往后,用户可以采取某些行动,要求我为 apollo 客户端设置一些以前没有的新标头。我最初想为此使用 react 上下文来传递设置的新标头并在内部使用它们,<Apollo />但我不确定这是否是正确的方法。
查看文档后,似乎只能在初始化时设置 apollo 标头?
apollo ×10
graphql ×9
react-apollo ×4
reactjs ×3
apollo-boost ×1
graphiql ×1
ios ×1
javascript ×1
node.js ×1
prisma ×1
swift ×1