GraphQL实现(后端:Node.js + GraphQL + Express)

2023-12-28 16:29:25 浏览数 (1)

后端(Node.js GraphQL Express):

代码语言:javascript复制
// server.js

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/taskapp', { useNewUrlParser: true, useUnifiedTopology: true });

const Task = mongoose.model('Task', {
  title: String,
  description: String,
});

const typeDefs = gql`
  type Task {
    _id: ID!
    title: String!
    description: String
  }

  type Query {
    tasks: [Task]
    task(id: ID!): Task
  }

  type Mutation {
    createTask(title: String!, description: String): Task
  }
`;

const resolvers = {
  Query: {
    tasks: () => Task.find(),
    task: (_, { id }) => Task.findById(id),
  },
  Mutation: {
    createTask: (_, { title, description }) => Task.create({ title, description }),
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
server.applyMiddleware({ app });

const PORT = 4000;
app.listen({ port: PORT }, () =>
  console.log(`Server running at http://localhost:${PORT}${server.graphqlPath}`)
);

确保安装相应的依赖,如@apollo/client, react-router-dom等。在实际项目中,可能需要更复杂的状态管理、错误处理和安全性实现。

0 人点赞