express graphql增删改查

app.ts

TypeScript 复制代码
import express, { Request, Response } from "express";
import { createHandler } from "graphql-http/lib/use/express";
import { buildSchema } from "graphql";
import { ruruHTML } from "ruru/server";
import cors from "cors";
import fs from "fs";
import path from "path";

// Int,Float,String,Boolean,ID
var schema = buildSchema(`
  #复杂对象类型
  type Article {
    id: ID
    title: String
    content: String
  }

  #复杂对象类型
  type User {
    id: ID
    name: String
    age: Int
    salary: Float
    articles: [Article] #数组
  }

  #查询列表,可查询数据名称类型
  #默认每个数据可以为空
  #加!不可以为空
  type Query {
    hello: String!
    foo: String!
    count: Int!
    salary: Float!
    isGood: Boolean
    userId: ID
    user: User
    tag: [String!]!
    #条件查询
    article(id: ID!, title: String): [Article]!
  }

  #参数类型
  input CreateArticleParams {
    title: String!
    content: String!
  }

  input UpdateArticleParams {
    id: ID
    title: String!
    content: String!
  }

  # 复杂数据类型
  type DeletionStatus {
    success: Boolean!
  }

  #修改入口点
  type Mutation {
    #createArticle(title: String!, content: String!): Article
    createArticle(params: CreateArticleParams): Article
    updateArticle(params: UpdateArticleParams): Boolean 
    deleteArticle(id: ID!): DeletionStatus
  }
`);

// resolver,对应schema中Query,Mutation进行处理
var root = {
  hello() {
    return "Hello world!"
  },
  foo() {
    return "foo";
  },
  count() {
    return 10;
  },
  salary() {
    return 14000.5;
  },
  isGood() {
    return true;
  },
  userId() {
    return '123456';
  },
  tag() {
    return ['ABC', 'DEF', 'GHI', 'JKL'];
  },
  user() {
    return {
      id: 'asdqwasdasd',
      name: 'String',
      age: 24,
      salary: 16000,
      articles: [
        { id: "12sdadasd", title: "abcdefg", content: "aaaaaaaaa" },
        { id: "asdsdqwe2", title: "abcdefg", content: "aaaaaaaaa" },
        { id: "qwee2qwe2", title: "abcdefg", content: "aaaaaaaaa" },
      ]
    }
  },
  // 条件查询
  article(args: { id: string }) {
    // console.log(args);
    return [
      { id: "12sdadasd", title: "abcdefg", content: "aaaaaaaaa" },
      { id: "asdsdqwe2", title: "abcdefg", content: "aaaaaaaaa" },
      { id: "qwee2qwe2", title: "abcdefg", content: "aaaaaaaaa" },
    ].filter(item => item.id === args.id);
  },
  // 添加,修改,删除
  createArticle({ params: { title, content } }: { params: { title: string, content: string } }) {
    console.log(title, content);
    return { id: "mokasdno", title, content };
  },
  updateArticle({ params }: { params: { [key: string]: string } }) {
    console.log(params);
    return true;
  },
  deleteArticle({ id }: { id: string }) {
    console.log(id);
    return { success: true };
  }
}

var app = express();

app.use(cors());

app.use(express.static(path.join(__dirname, 'public')));

app.all(
  "/graphql",
  createHandler({
    schema: schema,
    rootValue: root
  })
);

// Serve the GraphiQL IDE.
app.get("/", (_req: Request, res: Response) => {
  res.type("html")
  res.end(ruruHTML({ endpoint: "/graphql" }))
});

app.get('/index', (_req: Request, res: Response) => {
  res.type("html");
  res.end(fs.readFileSync(path.resolve(__dirname, './index.html'), 'utf-8'));
});

// Start the server at port
app.listen(4000, () => {
  console.log("Running a GraphQL API server at http://localhost:4000/graphql");
});

index.html

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="shortcut icon" href="react.svg" type="image/x-icon">
  <script src="https://cdn.staticfile.net/axios/1.6.5/axios.min.js"></script>
  <script src="https://cdn.staticfile.net/axios/1.6.5/axios.min.js.map"></script>
  <title>Document</title>
</head>

<body>

</body>
<script>
  // 普通查询
  axios({
    method: "POST",
    url: "http://localhost:4000/graphql",
    data: {
      // query: '{ foo, hello, count, salary, isGood, userId, tag, user{ name, age, articles { title, content } } }'
      query: 'query SearchData { foo, hello, count, salary, isGood, userId, tag, user{ name, age, articles { title, content } } }'
    }
  }).then(res => {
    if (res.data?.data) {
      console.log(res.data.data);
    } else {
      console.log(JSON.stringify(res.data.errors));
    }
  }).catch(err => {
    console.log(err);
  });

  // 条件查询
  axios({
    method: "POST",
    url: "http://localhost:4000/graphql",
    data: {
      // query: '{ article(id: "qwee2qwe2", title: "abcdefg") { id, title, content } }'
      // query: 'query asdadxc { article(id: "qwee2qwe2", title: "abcdefg") { id, title, content } }',
      query: 'query asdadxc($id: ID!, $title: String) { article(id: $id, title: $title) { id, title, content } }',
      // 使用variables进行字符串替换,免字符串拼接
      variables: {
        id: "qwee2qwe2",
        title: "abcdefg"
      }
    }
  }).then(res => {
    if (res.data?.data) {
      console.log(res.data.data);
    } else {
      console.log(JSON.stringify(res.data.errors));
    }
  }).catch(err => {
    console.log(err);
  });

  // 添加
  axios({
    method: "POST",
    url: "http://localhost:4000/graphql",
    data: {
      // query: 'mutation { createArticle(title: "abcdef", content: "texttttttt"){id,title,content} }'
      // query: 'mutation { createArticle(params: { title: "abcdef", content: "texttttttt" }){id,title,content} }'
      // query: 'mutation adasds { createArticle(params: { title: "abcdef", content: "texttttttt" }){id,title,content} }'
      query: `mutation asdasdsdd($create: CreateArticleParams) {
        createArticle(params: $create){
          id, title, content
        } 
      }`,
      variables: {
        create: {
          title: "abcdefg",
          content: "texttttttt"
        }
      }
    }
  }).then(res => {
    if (res.data?.data) {
      console.log(res.data.data);
    } else {
      console.log(JSON.stringify(res.data.errors));
    }
  }).catch(err => {
    console.log(err);
  });

  // 修改
  axios({
    method: "POST",
    url: "http://localhost:4000/graphql",
    data: {
      // query: 'mutation { createArticle(title: "abcdef", content: "texttttttt"){id,title,content} }'
      // query: 'mutation { createArticle(params: { title: "abcdef", content: "texttttttt" }){id,title,content} }'
      // query: 'mutation adasds { updateArticle(params: { id:"asdasdsad",title: "abcdef", content: "texttttttt" }) }'
      query: 'mutation lalalalala($update: UpdateArticleParams) { updateArticle(params: $update) }',
      variables: {
        update: {
          id: "asdasdsad",
          title: "abcdefg",
          content: "texttttttt"
        }
      }
    }
  }).then(res => {
    if (res.data?.data) {
      console.log(res.data.data);
    } else {
      console.log(JSON.stringify(res.data.errors));
    }
  }).catch(err => {
    console.log(err);
  });

  // 删除
  axios({
    method: "POST",
    url: "http://localhost:4000/graphql",
    data: {
      // query: 'mutation { createArticle(title: "abcdef", content: "texttttttt"){id,title,content} }'
      // query: 'mutation { createArticle(params: { title: "abcdef", content: "texttttttt" }){id,title,content} }'
      // query: 'mutation adasds { deleteArticle(id: "asdasdsad"){ success } }'
      query: 'mutation adasds($id: ID!) { deleteArticle(id: $id){ success } }',
      variables: {
        id: "asdasdsad",
      }
    }
  }).then(res => {
    if (res.data?.data) {
      console.log(res.data.data);
    } else {
      console.log(JSON.stringify(res.data.errors));
    }
  }).catch(err => {
    console.log(err);
  });

  // 同时执行多个修改
  axios({
    method: "POST",
    url: "http://localhost:4000/graphql",
    data: {
      query: `
      mutation adasds($id: ID!, $update: UpdateArticleParams, $create: CreateArticleParams) {
        deleteArticle(id: $id){
          success
        }
        createArticle(params: $create){
          id, title, content
        } 
        updateArticle(params: $update)
      }
      `,
      variables: {
        id: "asdasdsad",
        update: {
          id: "asdasdsad",
          title: "abcdefg",
          content: "texttttttt"
        },
        create: {
          title: "abcdefg",
          content: "texttttttt"
        }
      }
    }
  }).then(res => {
    if (res.data?.data) {
      console.log(res.data.data);
    } else {
      console.log(JSON.stringify(res.data.errors));
    }
  }).catch(err => {
    console.log(err);
  });

</script>

</html>
相关推荐
无我Code7 分钟前
前端-2025年末个人总结
前端·年终总结
文刀竹肃24 分钟前
DVWA -SQL Injection-通关教程-完结
前端·数据库·sql·安全·网络安全·oracle
LYFlied29 分钟前
【每日算法】LeetCode 84. 柱状图中最大的矩形
前端·算法·leetcode·面试·职场和发展
Bigger31 分钟前
Tauri(21)——窗口缩放后的”失焦惊魂”,游戏控制权丢失了
前端·macos·app
Bigger1 小时前
Tauri (20)——为什么 NSPanel 窗口不能用官方 API 全屏?
前端·macos·app
bug总结1 小时前
前端开发中为什么要使用 URL().origin 提取接口根地址
开发语言·前端·javascript·vue.js·html
一招定胜负2 小时前
网络爬虫(第三部)
前端·javascript·爬虫
Shaneyxs2 小时前
从 0 到 1 实现CloudBase云开发 + 低代码全栈开发活动管理小程序(13)
前端
半山烟雨半山青2 小时前
微信内容emoji表情包编辑器 + vue3 + ts + WrchatEmogi Editor
前端·javascript·vue.js
码途潇潇2 小时前
Vue 事件机制全面解析:原生事件、自定义事件与 DOM 冒泡完全讲透
前端·javascript