I am using apollo-graphql with postgres and now I want to be able to fetch my backend data into the apollo client. Its my first attempt at graphql and I did the following:
i.) created apollo-graphql server on localhost:4000 which also has the apollo graphql playground
ii.) Defined typeDefs and resolvers for my server
iii.) In typeDefs -> defined my schema
iv.) In resolvers -> just added a findAll Query (tried with both attributes and no parameters):
Query: {
me: () => account.findAll({attributes: ['user_id', 'username', 'email']})
}
v.) Then I added the postgres dbIndex I defined using sequelize ORM, into the server file (which I used in step iv above to query my db)
vi.) In my dbIndex file, I authenticate db using environment variables, get connected message, create db schema and export it.
After all these 6 steps, in apollo playground, I see null.
My list of files are below:
Server.js:
const {ApolloServer} = require('apollo-server');
const typeDefs = require('./schema');
const {account} = require('../database/dbIndex.js');
const resolvers = {
Query: {
me: () => account.findAll()
}
};
const server = new ApolloServer({
typeDefs,
resolvers
});
server.listen().then(({url}) => {
console.log(`Server ready at ${url}`);
});
dbIndex.js
const Sequelize = require('sequelize');
require('dotenv').config();
const sortDb = new Sequelize(
`${process.env.DATABASE}`,
process.env.DATABASE_USER,
process.env.DATABASE_PASSWORD,
{
dialect: 'postgres',
},
);
sortDb
.authenticate()
.then(() => {
console.log('Connected to DB');
})
.catch((err) => {
console.error('Unable to connect to DB', err);
});
const account = sortDb.define('account', {
user_id: {type: Sequelize.INTEGER},
username: {type: Sequelize.STRING},
email: {type: Sequelize.STRING}
});
module.exports.account = account;
schema.js
const {gql} = require('apollo-server');
const typeDef = gql
`
type Query {
"These are the queries we define in our query type"
me(user_id: ID): User
}
"How to define the structure of user? Below is an object type that does this:"
type User {
user_id: ID,
username: String,
email: String
}
`;
module.exports = typeDef;
Please help! Thanks in advance!