Fresh

28 Nov 2022

type Message = {
  id: string;
  author: string;
  message: string;
  createdAt: string;
};

export const handler: Handlers = {
  async GET(req, ctx) {
    const response = await fetch("http://localhost:4000/graphql", {
      method: "POST",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify({
        query: /* GraphQL */ `
          query GetAllMessages($first: Int!) {
            messageCollection(first: $first) {
              edges {
                node {
                  id
                  author
                  message
                  createdAt
                }
              }
            }
          }
        `,
        variables: {
          first: 10,
        },
      }),
    });

    if (!response.ok) {
      return ctx.render(null);
    }

    const { data } = await response.json();

    return ctx.render(data);
  },
  async POST(req, ctx) {
    const formData = await req.formData();
    const json = Object.fromEntries(formData);

    await fetch("http://localhost:4000/graphql", {
      method: "POST",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify({
        query: /* GraphQL */ `
          mutation AddNewMessage($author: String!, $message: String!) {
            messageCreate(input: { author: $author, message: $message }) {
              message {
                id
              }
            }
          }
        `,
        variables: {
          author: json.author,
          message: json.message,
        },
      }),
    });

    const response = await fetch("http://localhost:4000/graphql", {
      method: "POST",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify({
        query: /* GraphQL */ `
          query GetAllMessages($first: Int!) {
            messageCollection(first: $first) {
              edges {
                node {
                  id
                  author
                  message
                  createdAt
                }
              }
            }
          }
        `,
        variables: {
          first: 10,
        },
      }),
    });

    if (!response.ok) {
      return ctx.render(null);
    }

    const { data } = await response.json();

    return ctx.render(data);
  },
};