Our goal for this chapter is to run the following query:
query {
allLinks {
id
name
description
}
}
The expected response is a list of links fetched from the database.
Before we will add the first model, please decide where all models will be stored. I have one recommendation but of course, you can place all models in the place you want.
Create models
package and package. scala
with content:
package com.howtographql.scala.sangria
package object models {
}
All of the domain’s models will be placed in this file, so it will be easy to find them and in case of this tutorial easy to compare different versions and recognize if something changes. Now we can get back to creating our first model. Let’s start by defining a really basic model Link
.
In the file created above add the following case class:
case class Link(id: Int, url: String, description: String)
As you can see, Link
model has fewer fields than in the schema you saw in the first chapter, but no worries, we will improve the model in the future. Now we will focus on completing the execution stack so it would be better to keep this model simple. Add Link support to database Our simple database has to support this model and provide some data as well. Add following changes to the DBSchema. scala
:
import com.howtographql.scala.sangria.models._
//In the object body:
//1
class LinksTable(tag: Tag) extends Table[Link](tag, "LINKS"){
def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
def url = column[String]("URL")
def description = column[String]("DESCRIPTION")
def * = (id, url, description).mapTo[Link]
}
//2
val Links = TableQuery[LinksTable]
//3
val databaseSetup = DBIO.seq(
Links.schema.create,
Links forceInsertAll Seq(
Link(1, "http://howtographql.com", "Awesome community
driven GraphQL tutorial"),
Link(2, "http://graphql.org", "Official GraphQL web
page"),
Link(3, "https://facebook.github.io/graphql/", "GraphQL
specification")
)
)
We have just added the database definition of our first model.