【发布时间】:2019-08-26 18:01:29
【问题描述】:
我正在使用带有 postgres 的 apollo-graphql,现在我希望能够将我的后端数据获取到 apollo 客户端。这是我第一次尝试graphql,我做了以下事情: i.) 在 localhost:4000 上创建了 apollo-graphql 服务器,该服务器也有 apollo graphql 游乐场 ii.) 为我的服务器定义 typeDefs 和解析器 iii.) 在 typeDefs -> 定义了我的模式 iv.) 在解析器中 -> 刚刚添加了一个 findAll 查询(尝试使用属性和无参数):
Query: {
me: () => account.findAll({attributes: ['user_id', 'username', 'email']})
}
v.) 然后我将使用 sequelize ORM 定义的 postgres dbIndex 添加到服务器文件中(我在上面的步骤 iv 中使用它来查询我的数据库)
vi.) 在我的 dbIndex 文件中,我使用环境变量对 db 进行身份验证,获取连接的消息,创建 db 架构并将其导出。
在所有这 6 步之后,在阿波罗游乐场,我看到了 null。
我的文件列表如下:
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;
请帮忙!提前致谢!
【问题讨论】:
标签: node.js postgresql graphql apollo