javascript graphql瑜伽,简单的待办事项

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript graphql瑜伽,简单的待办事项相关的知识,希望对你有一定的参考价值。

const { GraphQLServer } = require('graphql-yoga');

let count = 2;
let todos = [{
  id: '0',
  content: 'Buy milk',
  isCompleted: true
},
{
  id: '1',
  content: 'Cook some lobster',
  isCompleted: false
}];

const typeDefs = `
  type Todo {
    id: ID!
    content: String!
    isCompleted: Boolean!
  }
  type Query {
    allTodos: [Todo!]!
    Todo(id: ID!): Todo!
  }
  type Mutation {
    createTodo(content: String!, isCompleted: Boolean!): Todo!
    updateTodo(id: ID!, content: String, isCompleted: Boolean): Todo!
    deleteTodo(id: ID!): Todo!
  }
`;

const resolvers = {
  Query: {
    allTodos: () => {
      return todos;
    },
    Todo: (_, { id }) => {
      const todo = todos.find(x => x.id === id);
      if (!todo) {
        throw new Error('Cannot find your todo!');
      }
      return todo;
    }
  },
  Mutation: {
    createTodo: (_, { content, isCompleted }) => {
      const newTodo = {
        id: count++,
        content,
        isCompleted
      }
      todos = [...todos, newTodo];
      return newTodo;
    },
    updateTodo: (_, { id, content, isCompleted }) => {
      let updatedTodo;

      todos = todos.map(todo => {
        if (todo.id === id) {
          updatedTodo = {
            id: todo.id,
            // for content and isCompleted, we first check if values are provided
            content: content !== undefined ? content : todo.content,
            isCompleted: isCompleted !== undefined ? isCompleted : todo.isCompleted
          }
          return updatedTodo;
        } else {
          return todo
        }
      });

      return updatedTodo;
    },
    deleteTodo: (_, { id }) => {
      const todoToDelete = todos.find(x => x.id === id);

      todos = todos.filter(todo => {
        return todo.id !== todoToDelete.id;
      });

      return todoToDelete;
    }
  }
}

const opts = {
  port: 7777,
  endpoint: '/graphql'
}

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

server.start(() => {
  console.log(
    `

以上是关于javascript graphql瑜伽,简单的待办事项的主要内容,如果未能解决你的问题,请参考以下文章

错误:使用约束时 Graphql 瑜伽中的指令约束

定义在graphql瑜伽的突变说法

用于解析器 GraphQL 瑜伽的 TypeScript 类型(在上下文中使用 prisma2)

瑜伽graphql服务器+棱镜服务器:多租户

Web前端期末大作业---响应式美女健身教练瑜伽馆网页设计(HTML+CSS+JavaScript+)实现

如何在 JavaScript 中进行简单的 GraphQL 查询