返回

Express + GraphQL构建cms框架应用案例

前端

前言

GraphQL是一个强大的数据查询语言,它允许客户端以声明式的方式从服务器请求数据。Express是一个轻量级的Node.js web框架,它非常适合构建REST API。本文将介绍如何使用Express和GraphQL构建一个简单的CMS框架。

数据模型

CMS框架需要一个数据模型来存储和管理数据。本文将使用MongoDB作为数据库。MongoDB是一个文档型数据库,它非常适合存储和管理JSON数据。

{
  "_id": "1",
  "title": "My First Blog Post",
  "content": "This is my first blog post.",
  "author": "John Doe",
  "date": "2023-03-08"
}

GraphQL Schema

GraphQL schema定义了客户端可以查询和突变的数据类型和字段。以下是一个简单的GraphQL schema示例:

type Query {
  posts: [Post]
  post(id: ID!): Post
}

type Mutation {
  createPost(title: String!, content: String!, author: String!): Post
  updatePost(id: ID!, title: String, content: String, author: String): Post
  deletePost(id: ID!): Post
}

type Post {
  id: ID!
  title: String!
  content: String!
  author: String!
  date: String!
}

Express Server

Express服务器负责处理客户端请求并返回响应。以下是一个简单的Express服务器示例:

const express = require('express');
const graphqlHTTP = require('express-graphql');
const { buildSchema } = require('graphql');

const schema = buildSchema(`
  type Query {
    posts: [Post]
    post(id: ID!): Post
  }

  type Mutation {
    createPost(title: String!, content: String!, author: String!): Post
    updatePost(id: ID!, title: String, content: String, author: String): Post
    deletePost(id: ID!): Post
  }

  type Post {
    id: ID!
    title: String!
    content: String!
    author: String!
    date: String!
  }
`);

const rootValue = {
  posts: () => {
    return posts;
  },
  post: ({ id }) => {
    return posts.find(post => post.id === id);
  },
  createPost: ({ title, content, author }) => {
    const newPost = {
      id: Date.now().toString(),
      title,
      content,
      author,
      date: new Date().toISOString()
    };
    posts.push(newPost);
    return newPost;
  },
  updatePost: ({ id, title, content, author }) => {
    const post = posts.find(post => post.id === id);
    if (title) { post.title = title; }
    if (content) { post.content = content; }
    if (author) { post.author = author; }
    return post;
  },
  deletePost: ({ id }) => {
    const post = posts.find(post => post.id === id);
    posts = posts.filter(post => post.id !== id);
    return post;
  }
};

const app = express();
app.use('/graphql', graphqlHTTP({
  schema,
  rootValue,
  graphiql: true
}));

app.listen(4000);

客户端

客户端可以使用任何支持GraphQL的库来向Express服务器发送请求。以下是一个简单的客户端示例:

import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

const client = new ApolloClient({
  uri: 'http://localhost:4000/graphql',
  cache: new InMemoryCache()
});

const query = gql`
  query {
    posts {
      id
      title
      content
      author
      date
    }
  }
`;

client.query({ query }).then(result => {
  console.log(result.data);
});

部署

Express + GraphQL框架可以部署到任何支持Node.js的平台上。以下是一些常见的部署选项:

  • Heroku
  • AWS Lambda
  • Google Cloud Functions
  • DigitalOcean App Platform

结论

本文介绍了如何使用Express和GraphQL构建一个简单的CMS框架。该框架可以作为构建更复杂CMS系统的基础,也可以直接用于小型网站。