要使用Apollo-Server将订阅功能连接到Postgres数据库,需要遵循以下步骤:
npm install apollo-server apollo-server-express graphql pg
schema.js
),定义你的GraphQL类型和订阅操作。以下是一个简单的示例:const { gql } = require('apollo-server');
const typeDefs = gql`
type Post {
id: ID!
title: String!
content: String!
}
type Query {
posts: [Post]
}
type Mutation {
createPost(title: String!, content: String!): Post
}
type Subscription {
postAdded: Post
}
`;
module.exports = typeDefs;
index.js
)中添加以下代码:const { ApolloServer, PubSub } = require('apollo-server');
const { Pool } = require('pg');
const typeDefs = require('./schema');
const pubsub = new PubSub();
// 创建Postgres数据库连接池
const pool = new Pool({
user: 'your_username',
host: 'your_host',
database: 'your_database',
password: 'your_password',
port: 5432,
});
// 从数据库获取帖子
const getPosts = async () => {
const client = await pool.connect();
const result = await client.query('SELECT * FROM posts');
client.release();
return result.rows;
};
// 将帖子插入到数据库
const createPost = async (title, content) => {
const client = await pool.connect();
const result = await client.query(
'INSERT INTO posts (title, content) VALUES ($1, $2) RETURNING *',
[title, content]
);
client.release();
return result.rows[0];
};
const resolvers = {
Query: {
posts: () => getPosts(),
},
Mutation: {
createPost: (_, { title, content }) => createPost(title, content),
},
Subscription: {
postAdded: {
subscribe: () => pubsub.asyncIterator(['POST_ADDED']),
},
},
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`Server running at ${url}`);
});
createPost
函数中添加以下代码:const createPost = async (title, content) => {
const client = await pool.connect();
const result = await client.query(
'INSERT INTO posts (title, content) VALUES ($1, $2) RETURNING *',
[title, content]
);
const post = result.rows[0];
// 发布新的帖子
pubsub.publish('POST_ADDED', { postAdded: post });
client.release();
return post;
};
现在,你可以使用Apollo-Server来订阅Postgres数据库中的数据了。例如,在前端应用中使用subscriptions-transport-ws
库来订阅postAdded
操作。
希望这可以帮助到你!