【问题标题】:Apollo Server and MySQL: How to get data direct from the database?Apollo Server 和 MySQL:如何直接从数据库中获取数据?
【发布时间】: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


    【解决方案1】:

    您是否查看了 Apollo Server 文档?有很多关于将数据源连接到服务器的好资料here

    有一个关于 SQL 连接的部分here。文档指出 Apollo 目前不提供专用的 SQL 连接,但通过一个示例向您展示了如何创建一个。

    【讨论】:

    • 我已经读过这个,但它只适用于直接写在代码中的数据。但我的完整数据在我的 mysql 数据库中。是否可以用变量替换模型中的数据。然后变量来自一个 php 文件,该文件为我提供数据并在模型中实现它们?
    猜你喜欢
    • 2022-01-14
    • 2017-12-07
    • 1970-01-01
    • 2012-12-29
    • 2012-11-20
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多