Links

Writing custom queries

This page provides an example of how to write custom queries.
You should have already read the CLI and files page before following this page's instructions.

Writing your first query

Let's write a simple query that returns the total number of entities in a randomly chosen table.
Make sure you have run npx @satsuma/cli init and npx @satsuma/cli codegen before proceeding.

Step 1: Add to typeDefs.ts

Open typeDefs.ts and add a new field to the Query type:
typeDefs: `
type RandomEntityCountTest {
count: Int!
tableName: String!
}
type Query {
randomEntityCountTest: RandomEntityCountTest!
}
`;

Step 2: Implement a helper

We're going to add a helper function to select a random item from an array
Open helpers.ts and add the following function:
// This import actually isn't necessary, as `_` is injected into the VM where this code is executed, but it makes your IDE happy.
import * as _ from "lodash";
export const helpers = {
randomItem: (array: any[]) => {
return _.sample(array);
},
};

Step 3: Implement the resolver

Open resolvers.ts and add a new resolver for the randomEntityCountTest field:
import { Context } from "./schema";
export const resolvers = {
Query: {
randomEntityCountTest: async (_root: any, _args: any, context: Context) => {
const { db } = context;
const allTables: string[] = Object.values(context.db.entities.tables); // Get a list of all tables in the database
const randomTable = context.helpers.randomItem(allTables);
const result = await db.entities(randomTable).count();
return {
tableName: randomTable,
count: result[0].count,
};
},
},
};

Step 4: Run the server

Run npx @satsuma/cli local --subgraph-name=<subgraph name> --version-name=<version name> --deploy-key <deploy key> to start the server.
You should see the following output:
🍊 Satsuma CLI version 1.1.94. Project Version: v1.
✔ Resolvers found
✔ TypeDefs found
✔ Helpers not found (optional)
✔ Fetching data from Satsuma API
✔ Getting metadata
✔ Loading code
🚶💨 Running server at http://localhost:4000/
If you visit http://localhost:4000/ in your browser (Mac users can cmd + double click on the URL), you should see the GraphQL playground.
Run the following query:
query ExampleQuery {
randomEntityCountTest {
count
tableName
}
}
You should see a result like this:
{
"data": {
"randomEntityCountTest": {
"count": 69420,
"tableName": "some_random_table"
}
}
}

Step 5: Deploy the custom queries

You can now deploy with
npx @satsuma/cli deploy --subgraph-name=<subgraph name> --version-name=<version name> --deploy-key <deploy key>
Once it's deployed, you can visit the Satsuma Website) to see find your custom query endpoint: