Argumentos
Instalamos npm i graphql-tools
index.js:
const { makeExecutableSchema } = require("graphql-tools");
const express = require("express");
const { graphqlHTTP } = require("express-graphql");
require('dotenv').config();
const { readFileSync } = require("fs");
const { join } = require("path");
const resolvers = require("./lib/resolvers");
const app = express();
const port = process.env.PORT || 3000;
//*Definiendo el esquema
const typeDefs = readFileSync(join(__dirname, "lib", "schema.graphql"), "utf-8");
const schema = makeExecutableSchema({ typeDefs, resolvers });
//* Nos traemos el schema desde donde se encuentra
//* Configurar los resolvers para que la query sí regrese información
app.use('/api', graphqlHTTP({
schema,
rootValue: resolvers,
graphiql: true
}));
app.listen(port, () => {
console.log(`Server running on port ${port}/api`);
});
resolvers.js:
const courses = [
{
_id: '1',
title: 'My title',
teacher: 'My teacher',
description: 'My description',
topic: 'Programming',
},
{
_id: '2',
title: 'My title 2',
teacher: 'My teacher 2',
description: 'My description 2',
topic: 'Programming 2',
},
{
_id: '3',
title: 'My title 3',
teacher: 'My teacher 3',
description: 'My description 3',
topic: 'Programming 3',
},
]
module.exports = {
Query: {
getCourses: () => { return courses },
getCourse: (root, args) => {
const course = courses.find(course => course._id === args.id)
return course
}
},
}
Y podemos hacer un query como el siguiente:
{
getCourse(id: "2"){
title
description
}
}