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:
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:
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"
}
]
}
}