【发布时间】:2021-11-30 00:23:20
【问题描述】:
目前我正在使用 ApolloServer/NodeJS 编写 GraphQL API。我有一个 MySQL 数据库。因为我是这个主题的新手,所以我不知道如何直接从我的数据库中获取数据。我的 api 将文章信息发送给客户端(这是我的 api 的唯一目的)。客户端可以通过 ID 搜索特定的文章(每篇文章/产品在数据库中都有一个特定的 ID。客户端输入的 id 应该与数据库中的 id 进行比较。所以如果 id = 1 那么 api 应该照看数据库中 id = 1 的文章,并将有关此文章的请求信息发送给客户端。(我知道这可能用 PHP 更好,但我用 PHP 有一些问题)。但我没有知道如何将其写入解析器。
这是我的解析器:
const models = require('../models');
module.exports = {
Query: {
article: (parent, {id}) => {
return models.articledata.find(
(c) => c.id == id
);
}
},
Node: {
__resolveType(node) {
if(node.toObject().name){
return 'Article';
}
}
}
}
这是我的模型:
let articledata = [{
id: 1,
name: 'title',
description: 'Beispiel',
imgs: 'www.test.de/img',
btnLink: 'shoplink',
headline: 'Spicy das neue Spiel',
introduction: 'Beispiel',
definition: 'Beispiel',
tutorial: 'Beispiel',
specsText: 'Beispiel',
endText: 'Beispiel',
age: 12,
duration: 30,
players: 12,
category: 'Beispiel',
designer: 'Beispiel',
language: 'Deutsch',
releaseDate: 2020,
topic: 'Beispiel',
}];
module.exports = { articledata };
这是我的 index.js:
const { ApolloServer } = require('apollo-server');
const schema = require('./schema');
const resolvers = require('./resolvers');
const server = new ApolloServer({
typeDefs: schema,
resolvers,
dataSources: () => {
articleAPI: new ArticleAPI()
}
})
//The listen-method launches a web server
server.listen().then(({ url }) => {
console.log('Server ready at ${url}');
});
当然,我在网上搜索过,但似乎没有什么对我有用。我很高兴你的帮助!!
【问题讨论】:
标签: javascript mysql node.js graphql apollo-server