我graphql-yoga/node目前正在努力。
我有一個 index.js 檔案,如下所示:
import { createServer } from "@graphql-yoga/node";
import { readFileSync } from "node:fs";
import Comment from "./resolvers/Comment";
import Query from "./resolvers/Query";
import Post from "./resolvers/Post";
import User from "./resolvers/User";
import Mutation from "./resolvers/Mutation";
import db from "./db";
const typeDefs = readFileSync("./src/schema.graphql", "utf-8");
const server = createServer({
schema: {
typeDefs,
resolvers: { Query, Mutation, Post, User, Comment },
context: { db },
},
});
server.start();
我有一個用于架構和決議器的單獨檔案。
架構檔案如下:
type Query {
posts(query: String): [Post!]!
users(query: String): [User!]!
comments(query: String): [Comment!]!
}
type Post {
id: ID!
title: String!
body: String!
isPublished: Boolean!
author: User!
comments: [Comment!]!
}
決議器如下:
const Post = {
author(parent, args, { db }, info) {
return db.users.find((user) => {
return user.id === parent.author;
});
},
comments(parent, args, { db }, info) {
return db.comments.filter((comment) => {
return comment.post === parent.id;
});
},
};
export { Post as default}
我有一個單獨的查詢檔案
const Query = {
posts(parent, args, { db }, info) {
if (!args.query) {
return db.posts;
}
return db.posts.filter((post) => {
const isTitleMatch = post.title.toLowerCase().includes(args.query.toLowerCase());
const isBodyMatch = post.body.toLowerCase().includes(args.query.toLowerCase());
return isTitleMatch || isBodyMatch;
});
}
}
export { Query as default };
db 是保存靜態資料的檔案。
const posts = [
{
id: "4",
title: "The alchemist",
body: "There is only one thing that makes a dream impossible to achieve: the fear of failure.",
isPublished: true,
author: "1",
},
{
id: "5",
title: "Dear stranger",
body: "the truth is you are at war with yourself thats why you find yourself at war with others.",
isPublished: false,
author: "3",
},
{
id: "6",
title: "Warren buffet",
body: "The most important thing to do if you find yourself in a hole is to stop digging.",
isPublished: true,
author: "3",
},
];
控制臺中沒有錯誤。一切似乎都處于良好的作業狀態。但是,當我嘗試如下所述運行 post 查詢時,我得到一個錯誤而不是回應。
query {
posts {
id
title
body
}
}
錯誤:
{
"errors": [
{
"message": "Unexpected error.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"posts"
]
}
],
"data": null
}
我不確定我做錯了什么。有人能幫我一下嗎?
uj5u.com熱心網友回復:
似乎您在服務器端遇到錯誤。你能分享你的終端/日志輸出嗎?
另外,該context選項應該在根級別,而不是在schema.
您可以嘗試以下嗎?
const server = createServer({
schema: {
typeDefs,
resolvers: { Query, Mutation, Post, User, Comment },
},
context: { db },
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/491617.html
標籤:节点.js api 图形 graphql-js
上一篇:API-網頁抓取
下一篇:Django模型中的一對多欄位
