currently I'm writing a GraphQL API with ApolloServer/NodeJS. I have a MySQL Database. Because I'm new at this topic, I dont have any idea how can I get data directly from my database. My api sends article information to the client (this is the only purpose of my api). The client can search a specific article via ID (every article/products has a specific ID in the database. The id which the client is typing in should be compared with the id in the database. So if the id = 1 then the api should look after the article which has the id = 1 in the DATABASE and sends the requested information about THIS article to the client. (I know that this might be better with PHP, but I have some trouble with PHP). But I don't know how I can write this into my resolver.
Here is my resolver:
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';
}
}
}
}
Here is my models:
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 };
And here is my 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}');
});
Of course I searched on the web, but nothing seems to work for me. I'm very glad about your help!!
Did you check out the Apollo Server documentation? There is a lot of good information of connecting data sources to your server here.
There's a section about SQL connections here. The documentation notes that Apollo does not provide dedicated SQL connections right now, but shows you how to create one by working through an example.