Skip to main content

Example: Container of Items

Creating the Models

First, create the SDL for your item

type Ball @createModel(accountRelation: LIST, description: "A ball to display") {
creator: DID! @accountReference
red: Int
green: Int
blue: Int
radius: Float
}

You will then save this to a file, such as ball.graphql. You can then add the model and get the id.

composedb composite:create --output ball.json ball.graphql cat ball.json | jq '.models | keys_unsorted[0]'

Next, create the SDL for your container, without references to items

type World @createModel(accountRelation: LIST, description: "Ball World") {
name: String! @string(minLength: 3, maxLength: 50)
}

Save this to a file and add as above. Then we will create a model to relate our item and container

type Ball @loadModel(id: "<id of ball>") {
id: ID!
}

type World @loadModel(id: "<id of world>"){
id: ID!
}

type BallRelation @createModel(accountRelation: LIST, description: "Relate a ball to our world") {
ballID: StreamID! @documentReference(model: "Ball")
ball: Ball! @relationDocument(property: "ballID")
worldID: StreamID! @documentReference(model: "World")
world: World! @relationDocument(property: "worldID")
}

For the relation, the ID will likely be the last model id. Finally, relate our container to our items

type BallRelation @loadModel(id: "<id of ball relation>") {
id: ID!
}

type World @loadModel(id: "<id of world>") {
balls: [BallRelation] @relationFrom(model: "BallRelation", property: "worldID")
}
caution

This is a view on top of the models, so you cannot require your items, such as with balls: [BallRelation!]

We can now merge all of these and deploy them as a composite.

composedb composite:merge ball.json world.json ball_relation.json world_relation.json --output=merged.json composedb composite:deploy merged.json composedb composite:compile merged.json runtime.json

Our composite is now ready to use. We can use it with graphiql

composedb graphql:server --graphiql runtime.json

Inserting Data

We can create an item with mutation

mutation CreateNewBall($i: CreateBallInput!){
createBall(input: $i){
document {
id
radius
}
}
}

and variables

{
"i": {
"content": {
"creator": "<some did key>",
"radius": 45,
"red": 10,
"green": 20,
"blue": 30
}
}
}

We can create a container with mutation

mutation CreateNewWorld($i: CreateWorldInput!){
createWorld(input: $i){
document {
id
}
}
}

and variables

{
"i": {
"content": {
"name": "test-world",
}
}
}

Finally we can define relations between items and the container with mutation

mutation CreateBallRelation($i: CreateBallRelationInput!){
createBallRelation(input: $i){
document {
id
}
}
}

and variables

{
"i": {
"content": {
"ballID": "<id from ball mutation>",
"worldID": "<id from world mutation>"
}
}
}

Query The Data

We can query for the container for the items, and from that find the items.

query {
worldIndex(first: 1) {
edges {
node {
id
name
balls(first: 5) {
edges {
node {
id
ballID
}
}
}
}
}
}
}