Create and Retrieve Links

CreateLinks

Lets implement CreateLink mutation; first we need a function to let us write a link to database. Create folders links and users inside internal directory, these packages are layers between database and our app.

In users.go we just defined a struct that represent users we get from database, But let me explain links.go part by part:

  • 1: definition of struct that represent a link.
  • 2: function that insert a Link object into database and returns it’s ID.
  • 3: our sql query to insert link into Links table. you see we used prepare here before db.Exec, the prepared statements helps you with security and also performance improvement in some cases. you can read more about it here.
  • 4: execution of our sql statement.
  • 5: retrieving Id of inserted Link.

Now we use this function in our CreateLink resolver:

Hopefully you understand this piece of code, we create a link object from input and save it to database then return newly created link(notice that we convert the ID to string with strconv.FormatInt). note that here we have 2 structs for Link in our project, one is use for our graphql server and one is for our database. run the server and open graphiql page to test what we just wrote:

links Query

Just like how we implemented CreateLink mutation we implement links query, we need a function to retrieve links from database and pass it to graphql server in our resolver. Create a function named GetAll

Return links from GetAll in Links query.

Now query Links at graphiql:

query {
  links {
    title
    address
    id
  }
}

result:

{
  "data": {
    "links": [
      {
        "title": "something",
        "address": "somewhere",
        "id": "1"
      }
    ]
  }
}

Next Chapter

Authentication

Implement authentication in gqlgen with jwt

Go to next chapter