GraphQL
Build schema-first GraphQL APIs with modular schema definitions, dependency-injected resolvers, feature services and a dedicated execution pipeline.
Understanding GraphQL in LykosJS
LykosJS provides a schema-first GraphQL starter built around the graphql package. Instead of defining API fields directly in TypeScript, you describe your API using GraphQL schema definition language (SDL) and implement the corresponding resolver methods in TypeScript.
The starter separates the GraphQL runtime from application features. The runtime handles schema construction, resolver registration and query execution, while feature modules contain their own schemas, resolvers and services.

1src/2├── graphql/3│ ├── graphql.executor.ts4│ ├── graphql.handler.ts5│ ├── graphql.resolvers.ts6│ └── graphql.schema.ts7│8├── modules/9│ └── users/10│ ├── users.module.ts11│ ├── users.resolver.ts12│ ├── users.service.ts13│ └── graphql-schema/14│ └── users.graphql15│16├── modules.ts17└── launch.tsThis architecture allows different application modules to contribute fields to a shared GraphQL schema without placing every type and resolver in one large file.
1. Create a GraphQL project
Start by running the LykosJS project creation command:
1bun create lykosjs my-appDuring the interactive setup, select GraphQL — schema-first with resolvers. You can also select the GraphQL template directly without using the interactive selection:
1bun create lykosjs my-app --template graphqlThe generated project includes the GraphQL runtime, an example feature module, resolver and service files, and a ready-to-configure application entry point.
2. Understand the GraphQL runtime
The GraphQL runtime consists of four dedicated files. Each file handles a different part of the request lifecycle.
graphql.schema.ts— discovers and merges feature GraphQL schema files and builds the executable GraphQL schema.graphql.resolvers.ts— resolves feature resolver instances through the Lykos dependency injection container.graphql.executor.ts— initializes the schema, collects resolver methods and executes GraphQL operations.graphql.handler.ts— validates the incoming GraphQL request body and delegates execution to the executor.
3. Define schemas with GraphQL SDL
LykosJS follows a schema-first approach. You define GraphQL types, queries, mutations and input objects in .graphql files instead of constructing the schema through TypeScript classes.
For example, the users feature defines its data type and available operations in users.graphql:
1type User {2 id: ID!3 name: String!4 email: String!5 createdAt: String!6}7 8input CreateUserInput {9 name: String!10 email: String!11 password: String!12}13 14input UpdateUserInput {15 name: String16 email: String17 password: String18}19 20type Query {21 users: [User!]!22 user(id: ID!): User23}24 25type Mutation {26 createUser(input: CreateUserInput!): User!27 updateUser(id: ID!, input: UpdateUserInput!): User28 deleteUser(id: ID!): User29}This schema describes the GraphQL API contract:
Userdefines the fields returned by user-related operations.CreateUserInputdescribes the required input for creating a user.UpdateUserInputdescribes the optional fields accepted when updating a user.Querydefines read operations.Mutationdefines operations that modify application data.
GraphQL types define the shape of the API, while resolver methods provide the actual implementation for the fields exposed by the schema.
4. Organize schemas by feature
Each feature can maintain its own .graphql file inside its module directory. The GraphQL schema builder recursively discovers these files under src/modules.
1src/modules/2├── users/3│ └── graphql-schema/4│ └── users.graphql5│6├── posts/7│ └── graphql-schema/8│ └── posts.graphql9│10└── comments/11 └── graphql-schema/12 └── comments.graphqlThe schema builder reads the discovered files, parses their definitions and combines them into a single GraphQL schema.
Root operation types receive special handling. Fields from separate Query, Mutation and Subscription definitions are merged into their corresponding root types.
1# users.graphql2type Query {3 users: [User!]!4}5 6# posts.graphql7type Query {8 posts: [Post!]!9}Both files contribute fields to the shared Query root. The resulting schema exposes both users andposts operations.
Other schema definitions are collected and passed to GraphQL's schema builder. Make sure your type definitions are compatible and do not introduce conflicting definitions.
5. Implement resolver classes
A resolver connects a GraphQL field to the operation that handles it. LykosJS uses regular TypeScript classes for resolvers, allowing them to receive dependencies through constructor injection.
The users resolver receives its service and exposes methods corresponding to the fields in the schema:
1import type {2 CreateUserInput,3 UpdateUserInput,4 UsersService,5} from './users.service'6 7interface UserArgs {8 id: string9}10 11interface CreateUserArgs {12 input: CreateUserInput13}14 15interface UpdateUserArgs {16 id: string17 input: UpdateUserInput18}19 20export class UsersResolver {21 constructor(22 private readonly usersService: UsersService,23 ) {}24 25 // Queries26 readonly users = async () => {27 return this.usersService.findAll()28 }29 30 readonly user = async (args: UserArgs) => {31 return this.usersService.findOne(args.id)32 }33 34 // Mutations35 readonly createUser = async (args: CreateUserArgs) => {36 return this.usersService.create(args.input)37 }38 39 readonly updateUser = async (args: UpdateUserArgs) => {40 return this.usersService.update(41 args.id,42 args.input,43 )44 }45 46 readonly deleteUser = async (args: UserArgs) => {47 return this.usersService.delete(args.id)48 }49}The resolver method names are important. The executor collects methods from resolver instances and uses their names as GraphQL root field names.
For example, the users method handles the Query.users field, while createUser handles the Mutation.createUser field.
Resolver methods receive their arguments as the first parameter. For example, a GraphQL field declared as user(id: ID!) receives an argument object containing id.
6. Keep business logic inside services
Resolvers should coordinate GraphQL operations rather than contain the application's business logic. The feature service owns the operations called by the resolver.
The generated users service defines the input structures and CRUD methods:
1export interface CreateUserInput {2 name: string3 email: string4 password: string5}6 7export interface UpdateUserInput {8 name?: string9 email?: string10 password?: string11}12 13export class UsersService {14 async create(input: CreateUserInput) {15 // Implement user creation.16 }17 18 async findAll() {19 // Implement fetching all users.20 }21 22 async findOne(id: string) {23 // Implement fetching a user by ID.24 }25 26 async update(id: string, input: UpdateUserInput) {27 // Implement updating a user.28 }29 30 async delete(id: string) {31 // Implement deleting a user.32 }33}The service receives the input or identifier supplied by the resolver and performs the corresponding operation.
This separation makes the service independent of GraphQL request execution. The same service can contain feature operations without needing to know how a GraphQL query was received.
7. Register GraphQL feature modules
GraphQL feature modules use the same LykosJS dependency injection module system. A module registers its service and resolver as providers.
1import { UsersService } from './users.service'2import { UsersResolver } from './users.resolver'3import { DIModule, bind } from 'lykosjs'4 5export class UsersModule extends DIModule {6 override imports = []7 override providers = [UsersService, bind(UsersResolver, UsersService)]8}The bind() helper describes how the resolver receives its service dependency. When the module is loaded, the dependency injection system can construct the resolver using the registered provider.
Collect your feature modules in the central module registry:
1import { UsersModule } from './modules/users/users.module'2 3export const Modules = [UsersModule]When adding another GraphQL feature, register its module here and include its resolver in the GraphQL resolver registry.
8. Register resolver instances
The GraphQL resolver registry connects the application's loaded modules to their resolver instances. The starter uses app.resolve()to retrieve each resolver through dependency injection.
1import type { Lykos } from 'lykosjs'2 3import { UsersModule } from '../modules/users/users.module'4import { UsersResolver } from '../modules/users/users.resolver'5 6export function createResolvers(app: Lykos): object[] {7 return [8 app.resolve(UsersModule, UsersResolver),9 ]10}For every new feature module, add its resolver to this registry. For example, a posts module would require its own resolver import and corresponding app.resolve() call.
9. Build the GraphQL schema
The schema builder is responsible for discovering and combining the feature schema files. It reads the .graphql files recursively from the modules directory.
It parses each file, collects its definitions and merges the root operation fields. The final definitions are passed to buildASTSchema() to create a GraphQL schema.
1import {2 buildASTSchema,3 Kind,4 parse,5} from 'graphql'6 7export async function buildSchema() {8 // Discover and read .graphql files.9 // Parse their definitions.10 // Merge Query, Mutation and Subscription fields.11 12 return buildASTSchema({13 kind: Kind.DOCUMENT,14 definitions,15 })16}This is a simplified illustration of the schema construction process. The actual starter implementation also checks for duplicate root fields before building the schema.
10. Initialize the GraphQL executor
The GraphQLExecutor connects the executable schema with the registered resolver instances. It has two main responsibilities: initialize the GraphQL runtime and execute operations.
1const resolvers = createResolvers(app)2 3const executor = new GraphQLExecutor(resolvers)4 5await executor.initialize()During initialization, the executor:
- Builds the shared GraphQL schema using
buildSchema(). - Collects methods from the provided resolver instances.
- Binds each resolver method to its original resolver instance.
- Stores the resulting field-to-function mapping as the root resolver object.
- Rejects duplicate resolver method names across different resolver instances.
Binding methods to their original instances ensures that their this references continue to point to the correct resolver object when GraphQL invokes them.
11. Understand resolver method mapping
The executor builds a root resolver object in which each key is a resolver method name and each value is its bound function.
1GraphQL schema field Resolver method2 3Query.users → UsersResolver.users4Query.user → UsersResolver.user5 6Mutation.createUser → UsersResolver.createUser7Mutation.updateUser → UsersResolver.updateUser8Mutation.deleteUser → UsersResolver.deleteUserThis is why the names of the resolver methods must correspond to the names of the GraphQL root fields.
The executor also walks the prototype chain of resolver instances to collect methods, while avoiding the base Object.prototype. When a subclass overrides a method, the overridden implementation is used for that resolver instance.
12. Handle incoming GraphQL requests
The GraphQLHandler provides a small request-handling layer between the HTTP route and the executor.
The generated request body has the following shape:
1export interface GraphQLBody {2 query: string3 variables?: Record<string, unknown>4}The handler checks that the request contains a non-empty string query. If the query is missing or invalid, it returns a GraphQL error object. Otherwise, it delegates execution to the executor.
1export class GraphQLHandler {2 constructor(3 private readonly executor: GraphQLExecutor,4 ) {}5 6 async handle(body: GraphQLBody) {7 if (8 typeof body?.query !== 'string' ||9 body.query.trim() === ''10 ) {11 return {12 errors: [13 { message: 'GraphQL query is required' },14 ],15 }16 }17 18 return this.executor.execute(19 body.query,20 body.variables,21 )22 }23}The executor then calls the GraphQL graphql() function with the initialized schema, query source, and optional variables.
13. Register the GraphQL HTTP endpoint
The starter exposes GraphQL through a regular LykosJS POST route. The route parses the incoming JSON body, passes it to the handler and returns the execution result as JSON.
1app.POST('/graphql', async (ctx, reply) => {2 const body = await ctx.json<GraphQLBody>()3 4 const result = await graphqlHandler.handle(body)5 6 return reply.json(result)7})The generated endpoint is POST /graphql. It accepts a JSON request body containing a GraphQL query and optionally a variables object.
Because this endpoint is registered through the regular LykosJS router, it uses the same HTTP server and route middleware pipeline as other application routes.
14. Complete application setup
The application entry point brings all GraphQL components together. The correct initialization order is important: load modules, resolve resolvers, initialize the executor, create the handler, register routes and finally start the HTTP server.
1import { Lykos } from 'lykosjs'2import { Modules } from './modules'3 4import { GraphQLExecutor } from './graphql/graphql.executor'5import { GraphQLHandler } from './graphql/graphql.handler'6import { createResolvers } from './graphql/graphql.resolvers'7 8async function launch() {9 const app = new Lykos()10 11 // Load feature modules.12 app.modules(Modules)13 14 // Resolve feature resolvers through DI.15 const executor = new GraphQLExecutor(createResolvers(app))16 17 // Build the schema and resolver mapping.18 await executor.initialize()19 20 // Create the request handler.21 const graphqlHandler = new GraphQLHandler(executor)22 23 app.GET('/', async (ctx, reply) => reply.send('Welcome to LykosJS 🐺'))24 25 // Register the GraphQL endpoint.26 app.POST('/graphql', async (ctx, reply) => {27 const body = await ctx.json<GraphQLBody>()28 29 const result = await graphqlHandler.handle(body)30 31 return reply.json(result)32 })33 34 // Start the server.35 app.listen(4000, () => console.log('🐺 LykosJS is running at http://localhost:4000'))36}37 38launch().catch((error: unknown) => {39 console.error('[LykosJS] Failed to start application:', error)40 process.exit(1)41})This setup keeps GraphQL initialization outside the request handler. The schema and resolver mapping are prepared once during application startup rather than rebuilt for every request.
15. Execute GraphQL queries
Queries are used to retrieve data from the GraphQL API. The users feature exposes a users query that returns a list of users.
1query {2 users {3 id4 name5 email6 createdAt7 }8}You can also request a single user by ID:
1query GetUser($id: ID!) {2 user(id: $id) {3 id4 name5 email6 }7}GraphQL lets the client specify which fields it needs in the response. The fields must exist on the corresponding type in the schema.
16. Execute GraphQL mutations
Mutations represent operations that modify application data. The users schema exposes create, update and delete operations.
Create a user:
1mutation CreateUser($input: CreateUserInput!) {2 createUser(input: $input) {3 id4 name5 email6 }7}Update an existing user:
1mutation UpdateUser(2 $id: ID!3 $input: UpdateUserInput!4) {5 updateUser(id: $id, input: $input) {6 id7 name8 email9 }10}Delete a user:
1mutation DeleteUser($id: ID!) {2 deleteUser(id: $id) {3 id4 name5 }6}The resolver receives the operation arguments and delegates the requested action to the corresponding service method.
17. Send requests over HTTP
The GraphQL endpoint accepts POST requests containing a JSON body. You can test it using curl:
1curl -X POST http://localhost:4000/graphql \2 -H 'content-type: application/json' \3 -d '{4 "query": "query { users { id name email } }"5 }'To send variables, include a variables object alongside the query:
1curl -X POST http://localhost:4000/graphql \2 -H 'content-type: application/json' \3 -d '{4 "query": "query GetUser($id: ID!) { user(id: $id) { id name } }",5 "variables": {6 "id": "user-1"7 }8 }'The handler forwards the query and variables to the executor, which returns the GraphQL execution result.
18. Test GraphQL resolvers and services
The starter uses bun:test for its tests. It provides separate test files for the feature service and resolver.
Service tests verify the generated service methods and their current placeholder behavior. Resolver tests use mocked service methods to verify that resolver operations delegate the correct arguments and return the service results.
1import { describe, expect, it, mock } from 'bun:test'2import { UsersResolver } from '../users.resolver'3 4const user = {5 id: 'user-1',6 name: 'Zen',7 email: 'zen@example.com',8}9 10const usersService = {11 findAll: mock(async () => [user]),12 findOne: mock(async (id: string) => user),13}14 15const resolver = new UsersResolver(16 usersService as never,17)18 19describe('UsersResolver', () => {20 it('should return all users', async () => {21 const result = await resolver.users()22 23 expect(result).toEqual([user])24 expect(usersService.findAll).toHaveBeenCalledTimes(1)25 })26 27 it('should find a user by ID', async () => {28 const result = await resolver.user({29 id: 'user-1',30 })31 32 expect(result).toEqual(user)33 expect(usersService.findOne).toHaveBeenCalledWith(34 'user-1',35 )36 })37})The example illustrates the resolver testing approach. The generated tests also cover mutations, missing records and service errors. They do not replace tests for the complete HTTP endpoint or the actual database implementation.
1bun test19. GraphQL development workflow
When adding a new GraphQL feature, follow the same modular workflow:
- Create a feature module and its service.
- Define the feature's GraphQL types, queries and mutations in a
.graphqlfile. - Implement a resolver method for each root field that should be handled by the feature.
- Register the service and resolver in the feature module.
- Add the feature module to the central
Modulesregistry. - Add the resolver instance to
createResolvers(). - Initialize the executor after loading modules.
- Test resolver delegation and service behavior.
Important implementation boundaries
The GraphQL starter provides schema discovery, root field merging, dependency-injected resolver registration and GraphQL execution. Some application-level capabilities still need implementation.
- Database persistence must be implemented inside your feature services.
- Resolver methods must be implemented for the fields you want to execute.
- Authentication and authorization are not configured by the GraphQL starter code shown here.
- Input validation is not automatically applied by the shown GraphQL handler.
- The generated handler accepts a query and optional variables; it does not show support for subscriptions or WebSocket GraphQL transport.