DEV Community

Cover image for Slack Clone with React | Semantic UI | GraphQL | PostgresSQL (PART 4)
AjeaS
AjeaS

Posted on

Slack Clone with React | Semantic UI | GraphQL | PostgresSQL (PART 4)

Previously, we got our database started. You can find that article here.

Today, we will talk shortly about Graphql queries and mutations.

GraphQL API in a Nutshell

Types: Queries, Mutations, custom

Types define what your endpoints are and **describe* what they should return. *

Queries look like this =>

type Query {
    getColors: [String]!
    getNames: [String]
    sayName: String!
  }
Enter fullscreen mode Exit fullscreen mode

(EX: getColors needs to return an array of strings, which will be color names). The exclamation mark means the item cannot be null. The type query category will be your GET endpoints.

Mutations look like this =>

type Mutation {
    sayHello(message: String!): String!
  }
Enter fullscreen mode Exit fullscreen mode

The same rules apply to Mutations. The only difference is, The type mutation category will be your POST, PUT, DELETE endpoints.

Custom types look like this =>

type User {
  name: String!
  age: Int!
  bio: String!
}
Enter fullscreen mode Exit fullscreen mode

This is a regular custom object with 3 properties that describe it (name, age, bio) which you can use like so =>

type Query{
/** returns array of users */
  getUsers: [User!]
  getUser: User!
}

type Mutation {
/** creates a user, returns that user */
  createUser: (name: String!, age: Int!, bio:String!): User
}
Enter fullscreen mode Exit fullscreen mode

Resolvers: Queries and Mutations

*Resolvers returns the actual data that you described in the types. Your query and mutation names need to match the ones you described in your type query category *

Queries look like this in resolvers =>

Query: {
    getColors: () => ["blue", "yellow", "green"],
    sayName: () => "Ajea!"
}
Enter fullscreen mode Exit fullscreen mode

Mutations look like this in resolvers =>

/**args is whatever data you passed in (as an object), when you call this type. There are more params by default but we don't need them, thats way we use `_,`*/ 
Mutation: {
   sayHello: (_, args) => {
      return `hello ${args.message}`
   },
   createUser: async (_, args) => {
      try{
        /** async code happens **/
       /** create user with args data into DB, and then return user*/
      }catch(err){
       console.log(err)
      }
  }
}
Enter fullscreen mode Exit fullscreen mode

Don't worry if all of this is still fuzzy, it will start making sense once we create our real queries and mutations in the next article. In the next one, well create those and actually test them out in the Graphql server. I just wanted to go over the overview of GraphQL API.

Hope that helps so far, if not feel free to let me know : )

Top comments (0)