API Extensions
Squid alows to extend the GraphQL auto-generated schema with custom queries. To do that, one can define GraphQL query resolvers in the designated module src/server-extension/resolvers. Note that all resolver classes must be exported.
It is convenient to import TypeGraphQL and use the annotations provided by the library to define the query arguments and return types.
Custom resolvers are typically used in combination with TypeORM EntityManager. It is automatically enabled by dependency injection when defined as a constructor argument.
A custom resolver may then look as follows:
1
import { Arg, Field, ObjectType, Query, Resolver } from 'type-graphql'
2
import type { EntityManager } from 'typeorm'
3
import { MyEntity } from '../../model/generated'
4
5
// Define custom GraphQL ObjectType of the query result
6
@ObjectType()
7
export class MyQueryResult {
8
@Field(() => Number, { nullable: false })
9
total!: number
10
11
@Field(() => Number, { nullable: false })
12
max!: number
13
14
constructor(props: Partial<MyQueryResult>) {
15
Object.assign(this, props);
16
}
17
}
18
19
@Resolver()
20
export class MyResolver {
21
// Set by depenency injection
22
constructor(private tx: () => Promise<EntityManager>) {}
23
24
@Query(() => [MyQueryResult])
25
async myQuery(): Promise<MyQueryResult[]> {
26
const manager = await this.tx()
27
// execute custom SQL query
28
const result: = await manager.getRepository(MyEntity).query(
29
`SELECT
30
COUNT(x) as total,
31
MAX(y) as max
32
FROM my_entity
33
GROUP BY month`)
34
return result
35
}
36
}
Copied!
Some great examples of custom Squid resolvers can be spotted in the wild in the Rubik repo by KodaDot.
For more examples of resolvers, see TypeGraphQL repo
Copy link