Project Structure
Explore the REST and GraphQL project architectures generated by the LykosJS CLI, understand the purpose of each file, and see how modules, dependency injection, and request handling fit together.
LykosJS provides two starter templates: REST and GraphQL. Both follow a modular architecture, allowing you to organize application features independently while keeping the application entry point simple.
REST architecture
The REST template organizes each feature into a module. A typical feature contains a controller, router, service, validation rules, schemas, and tests.

Directory structure
1src/2├── launch.ts3├── modules.ts4└── modules/5 └── users/6 ├── users.controller.ts7 ├── users.module.ts8 ├── users.route.ts9 ├── users.service.ts10 ├── rules/11 │ ├── create.ts12 │ └── update.ts13 ├── schemas/14 │ └── user.schema.ts15 └── tests/16 ├── users.controller.test.ts17 └── users.service.test.tsApplication entry point
The launch.ts file is the application entry point. It creates the LykosJS instance, registers the application modules, defines the root route, and starts the HTTP server.
1import { Lykos } from 'lykosjs'2import { Modules } from './modules'3 4async function launch() {5 const app = new Lykos()6 7 app.GET('/', async (ctx, reply) => reply.send('Welcome to LykosJS 🐺'))8 9 app.modules(Modules)10 11 app.listen(4000, () => console.log('🐺 LykosJS is running at http://localhost:4000'))12}13 14launch().catch((error: unknown) => {15 console.error('🐺 [LykosJS] Failed to start application:', error)16 process.exit(1)17})Module registration
The modules.ts file provides a central registry for application modules. Add each feature module to the exported array so it can be registered with the application.
1import { UsersModule } from './modules/users/users.module'2 3export const Modules = [UsersModule]Feature module
Each feature module extends DIModule and declares its providers, controllers, routers, and authentication configuration.
The bind() function connects classes with their constructor dependencies, while defineAuth()defines the module's authentication configuration.
1import {2 AuthMiddleware,3 bind,4 defineAuth,5 Lykos,6 DIModule,7} from 'lykosjs'8 9import { UsersService } from './users.service'10import { UsersController } from './users.controller'11import { UsersRouter } from './users.route'12 13export class UsersModule extends DIModule {14 override imports = []15 16 override providers = [UsersService]17 18 override controllers = [19 bind(UsersController, UsersService),20 ]21 22 override routers = [23 bind(UsersRouter, Lykos, UsersController, AuthMiddleware),24 ]25 26 override auth = defineAuth({27 verifier: UsersController,28 mode: 'bearer',29 })30}Controller
Controllers contain the request handlers for a feature. They receive their dependencies through constructor injection and delegate application operations to services.
The REST starter uses ContextHandler to type its route handlers.
1import type { ContextHandler } from 'lykosjs'2import type { UsersService } from './users.service'3 4export class UsersController {5 constructor(6 private readonly usersService: UsersService,7 ) {}8 9 readonly create: ContextHandler = async (ctx, reply) => {10 // TODO: Implement creation logic.11 const result = await this.usersService.create()12 }13 14 readonly findAll: ContextHandler = async (ctx, reply) => {15 // TODO: Implement fetching all records.16 const result = await this.usersService.findAll()17 }18 19 readonly findOne: ContextHandler = async (ctx, reply) => {20 // TODO: Implement fetching a record by ID.21 const result = await this.usersService.findOne()22 }23 24 readonly update: ContextHandler = async (ctx, reply) => {25 // TODO: Implement updating a record.26 const result = await this.usersService.update()27 }28 29 readonly delete: ContextHandler = async (ctx, reply) => {30 // TODO: Implement deleting a record.31 const result = await this.usersService.delete()32 }33 34 verifyToken(token: string) {35 // TODO: Implement token verification.36 return null37 }38}Router
The router registers HTTP endpoints and connects them to controller handlers. It also demonstrates how to organize public and protected routes using route groups and authentication middleware.
1import type { Lykos } from 'lykosjs'2import { AuthMiddleware } from 'lykosjs'3import { UsersController } from './users.controller'4 5export class UsersRouter {6 constructor(7 private readonly app: Lykos,8 private readonly controller: UsersController,9 private readonly authMiddleware: AuthMiddleware,10 ) {}11 12 register(): void {13 // Public routes14 this.app.group('/api/users', (guest) => {15 guest.GET('/', this.controller.findAll)16 guest.GET('/:id', this.controller.findOne)17 })18 19 // Protected routes20 this.app.group(21 '/api/users',22 (auth) => {23 auth.POST('/', this.controller.create)24 auth.PUT('/:id', this.controller.update)25 auth.DELETE('/:id', this.controller.delete)26 },27 this.authMiddleware.middleware,28 )29 }30}Service
Services contain the application's business operations. The controller delegates its work to the service instead of embedding application logic inside request handlers.
1export class UsersService {2 constructor() {}3 4 async create() {5 // TODO: Implement creation logic.6 }7 8 async findAll() {9 // TODO: Implement fetching all records.10 }11 12 async findOne() {13 // TODO: Implement fetching a record by ID.14 }15 16 async update() {17 // TODO: Implement updating a record.18 }19 20 async delete() {21 // TODO: Implement deleting a record.22 }23}Validation rules
The rules/ directory contains validation definitions for feature inputs. The REST template demonstrates the framework's defineSchema()and Validator APIs.
For example, create.ts defines the creation rule, while update.ts reuses that definition.
1// rules/create.ts2import { defineSchema, Validator } from 'lykosjs'3 4export const CreateUserRule = defineSchema({5 // name: Validator.string(3, 50).required(),6 // email: Validator.string(3, 255).email().required(),7 // password: Validator.string(8, 40).required().confirmed(),8})1// rules/update.ts2import { CreateUserRule } from './create'3 4export const UpdateUserRule = CreateUserRuleData schema
The schemas/ directory is dedicated to defining database schemas for each feature, which are used with the ORM to organize the data structure and specify fields and their types. The template currently includes a UserSchema class for defining the user schema.
1// schemas/user.schema.ts2export class UserSchema {}Tests
The REST template includes separate tests for the controller and service, using Bun's test runner. The generated tests verify that the classes can be instantiated and expose their expected methods.
1// tests/users.service.test.ts2import { describe, expect, test } from 'bun:test'3import { UsersService } from '../users.service'4 5describe('UsersService', () => {6 const usersService = new UsersService()7 8 test('should be defined', () => {9 expect(usersService).toBeDefined()10 })11 12 test('should expose all service methods', () => {13 expect(typeof usersService.create).toBe('function')14 expect(typeof usersService.findAll).toBe('function')15 expect(typeof usersService.findOne).toBe('function')16 expect(typeof usersService.update).toBe('function')17 expect(typeof usersService.delete).toBe('function')18 })19})GraphQL architecture
The GraphQL template follows the same feature-oriented organization but uses resolvers instead of REST controllers and routers.
It also includes a GraphQL execution layer that collects module resolvers, builds a unified schema from GraphQL files, and handles incoming GraphQL requests.

Directory structure
1src/2├── launch.ts3├── modules.ts4├── graphql/5│ ├── graphql.executor.ts6│ ├── graphql.handler.ts7│ ├── graphql.resolvers.ts8│ └── graphql.schema.ts9└── modules/10 └── users/11 ├── users.module.ts12 ├── users.resolver.ts13 ├── users.service.ts14 ├── graphql-schema/15 │ └── users.graphql16 └── tests/17 ├── users.resolver.test.ts18 └── users.service.test.tsApplication entry point
The GraphQL entry point initializes the application modules, creates the resolver instances through dependency injection, builds the GraphQL schema, and registers the POST /graphql endpoint.
1import { Lykos } from 'lykosjs'2import { Modules } from './modules'3import { GraphQLExecutor } from './graphql/graphql.executor'4import {5 GraphQLHandler,6 type GraphQLBody,7} from './graphql/graphql.handler'8import { createResolvers } from './graphql/graphql.resolvers'9 10async function launch() {11 const app = new Lykos()12 13 app.modules(Modules)14 15 // Resolvers are created through DI.16 const executor = new GraphQLExecutor(createResolvers(app))17 18 // Build the schema from module GraphQL files.19 await executor.initialize()20 21 const graphqlHandler = new GraphQLHandler(executor)22 23 app.GET('/', async (ctx, reply) =>24 reply.send('Welcome to LykosJS 🐺'),25 )26 27 app.POST('/graphql', async (ctx, reply) => {28 const body = await ctx.json<GraphQLBody>()29 30 const result = await graphqlHandler.handle(body)31 32 return reply.json(result)33 })34 35 app.listen(4000, () =>36 console.log('🐺 LykosJS is running at http://localhost:4000'),37 )38}39 40launch().catch((error: unknown) => {41 console.error('[LykosJS] Failed to start application:', error)42 process.exit(1)43})Module registration
Just like the REST template, GraphQL uses a central module registry.
1// modules.ts2import { UsersModule } from './modules/users/users.module'3 4export const Modules = [UsersModule]Feature module
A GraphQL feature module registers its service and resolver as providers. The resolver receives its service through dependency injection.
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 8 override providers = [9 UsersService,10 bind(UsersResolver, UsersService),11 ]12}Service
The service contains the operations used by GraphQL resolvers. Unlike the REST starter, the GraphQL service defines explicit input types and receives the relevant arguments for each operation.
1// users.service.ts2export interface CreateUserInput {3 name: string4 email: string5 password: string6}7 8export interface UpdateUserInput {9 name?: string10 email?: string11 password?: string12}13 14export class UsersService {15 async create(input: CreateUserInput) {16 // Implement user creation.17 }18 19 async findAll() {20 // Implement fetching all users.21 }22 23 async findOne(id: string) {24 // Implement fetching a user by ID.25 }26 27 async update(id: string, input: UpdateUserInput) {28 // Implement updating a user.29 }30 31 async delete(id: string) {32 // Implement deleting a user.33 }34}Resolver
Resolvers connect GraphQL fields to application operations. Each resolver method delegates to the corresponding service method.
The method names correspond to the fields defined in the GraphQL 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(args.id, args.input)41 }42 43 readonly deleteUser = async (args: UserArgs) => {44 return this.usersService.delete(args.id)45 }46}GraphQL schema
Each feature can define its own .graphqlfile inside its graphql-schema/ directory. The Users schema defines the user type, input types, queries, and mutations.
1# graphql-schema/users.graphql2 3type User {4 id: ID!5 name: String!6 email: String!7 createdAt: String!8}9 10input CreateUserInput {11 name: String!12 email: String!13 password: String!14}15 16input UpdateUserInput {17 name: String18 email: String19 password: String20}21 22type Query {23 users: [User!]!24 user(id: ID!): User25}26 27type Mutation {28 createUser(input: CreateUserInput!): User!29 updateUser(id: ID!, input: UpdateUserInput!): User30 deleteUser(id: ID!): User31}Resolver registration
The graphql.resolvers.ts file creates resolver instances through the application's dependency injection container using app.resolve(). Register each feature's resolver here.
1import type { Lykos } from 'lykosjs'2import { UsersModule } from '../modules/users/users.module'3import { UsersResolver } from '../modules/users/users.resolver'4 5export function createResolvers(app: Lykos): object[] {6 return [7 app.resolve(UsersModule, UsersResolver),8 ]9}GraphQL schema builder
The schema builder reads all .graphqlfiles recursively from the modules directory. It combines their definitions into a single schema and merges fields belonging to the root types: Query, Mutation, andSubscription.
Duplicate fields within the same root type cause schema construction to fail with an error.
1import { readdir, readFile } from 'node:fs/promises'2import { join } from 'node:path'3import { fileURLToPath } from 'node:url'4import {5 buildASTSchema,6 Kind,7 parse,8 type DefinitionNode,9 type FieldDefinitionNode,10 type GraphQLSchema,11 type ObjectTypeDefinitionNode,12} from 'graphql'13 14const MODULES_DIR = fileURLToPath(15 new URL('../modules', import.meta.url),16)17 18const ROOT_TYPES = ['Query', 'Mutation', 'Subscription']19 20export async function buildSchema(): Promise<GraphQLSchema> {21 const files = (22 await readdir(MODULES_DIR, { recursive: true })23 ).filter((file) => file.endsWith('.graphql'))24 25 const definitions: DefinitionNode[] = []26 27 const roots = new Map<28 string,29 {30 node: ObjectTypeDefinitionNode31 fields: FieldDefinitionNode[]32 }33 >()34 35 for (const file of files.sort()) {36 const document = parse(37 await readFile(join(MODULES_DIR, file), 'utf-8'),38 )39 40 for (const definition of document.definitions) {41 if (42 definition.kind !== Kind.OBJECT_TYPE_DEFINITION ||43 !ROOT_TYPES.includes(definition.name.value)44 ) {45 definitions.push(definition)46 continue47 }48 49 const root = roots.get(definition.name.value) ?? {50 node: definition,51 fields: [],52 }53 54 for (const field of definition.fields ?? []) {55 if (56 root.fields.some(57 (existing) => existing.name.value === field.name.value,58 )59 ) {60 throw new Error(61 `GraphQL field "${definition.name.value}.${field.name.value}" is defined twice (${file})`,62 )63 }64 65 root.fields.push(field)66 }67 68 roots.set(definition.name.value, root)69 }70 }71 72 for (const { node, fields } of roots.values()) {73 definitions.push({ ...node, fields })74 }75 76 return buildASTSchema({77 kind: Kind.DOCUMENT,78 definitions,79 })80}GraphQL executor
The executor initializes the unified schema and combines the registered resolver methods into a root value. It then passes incoming operations and variables to the GraphQL execution function.
1import {2 graphql,3 type ExecutionResult,4 type GraphQLSchema,5} from 'graphql'6 7import { buildSchema } from './graphql.schema'8 9type ResolverFn = (...args: unknown[]) => unknown10 11export class GraphQLExecutor {12 private schema!: GraphQLSchema13 14 private rootValue: Record<string, ResolverFn> = {}15 16 constructor(private readonly resolvers: object[]) {}17 18 async initialize() {19 this.schema = await buildSchema()20 this.rootValue = this.mergeResolvers()21 }22 23 execute(24 source: string,25 variables?: Record<string, unknown>,26 ): Promise<ExecutionResult> {27 return graphql({28 schema: this.schema,29 source,30 rootValue: this.rootValue,31 variableValues: variables,32 })33 }34 35 private mergeResolvers(): Record<string, ResolverFn> {36 const root: Record<string, ResolverFn> = {}37 const owners = new Map<string, object>()38 39 for (const resolver of this.resolvers) {40 let target: object | null = resolver41 42 while (target && target !== Object.prototype) {43 for (const name of Object.getOwnPropertyNames(target)) {44 const descriptor = Object.getOwnPropertyDescriptor(45 target,46 name,47 )48 49 if (50 name === 'constructor' ||51 typeof descriptor?.value !== 'function'52 ) {53 continue54 }55 56 const owner = owners.get(name)57 58 if (owner === resolver) continue59 60 if (owner !== undefined) {61 throw new Error(62 `GraphQL resolver "${name}" is defined in more than one resolver`,63 )64 }65 66 owners.set(name, resolver)67 68 root[name] = (69 descriptor.value as ResolverFn70 ).bind(resolver)71 }72 73 target = Object.getPrototypeOf(target)74 }75 }76 77 return root78 }79}GraphQL request handler
The handler validates the incoming request body before forwarding the query and optional variables to the executor.
1import type { GraphQLExecutor } from './graphql.executor'2 3export interface GraphQLBody {4 query: string5 variables?: Record<string, unknown>6}7 8export class GraphQLHandler {9 constructor(10 private readonly executor: GraphQLExecutor,11 ) {}12 13 async handle(body: GraphQLBody) {14 if (15 typeof body?.query !== 'string' ||16 body.query.trim() === ''17 ) {18 return {19 errors: [{ message: 'GraphQL query is required' }],20 }21 }22 23 return this.executor.execute(24 body.query,25 body.variables,26 )27 }28}Tests
The GraphQL template includes tests for both services and resolvers using Bun's test runner.
The service tests verify the current placeholder methods resolve with undefined. The resolver tests use mocked service methods to verify that queries and mutations delegate the expected arguments, return service results, and propagate service errors.
1// tests/users.service.test.ts2import { describe, expect, it, beforeEach } from 'bun:test'3import { UsersService } from '../users.service'4 5describe('UsersService', () => {6 let service: UsersService7 8 beforeEach(() => {9 service = new UsersService()10 })11 12 it('should resolve create with undefined', async () => {13 await expect(14 service.create({15 name: 'Zen',16 email: 'zen@example.com',17 password: 'password123',18 }),19 ).resolves.toBeUndefined()20 })21 22 it('should resolve findAll with undefined', async () => {23 await expect(service.findAll()).resolves.toBeUndefined()24 })25 26 it('should resolve findOne with undefined', async () => {27 await expect(28 service.findOne('user-1'),29 ).resolves.toBeUndefined()30 })31 32 it('should resolve update with undefined', async () => {33 await expect(34 service.update('user-1', { name: 'Updated Zen' }),35 ).resolves.toBeUndefined()36 })37 38 it('should resolve delete with undefined', async () => {39 await expect(40 service.delete('user-1'),41 ).resolves.toBeUndefined()42 })43})REST vs. GraphQL
Both templates use LykosJS modules and dependency injection, but they organize request handling differently.
- REST: Uses controllers and routers to register HTTP endpoints and handle requests.
- GraphQL: Uses resolvers to map GraphQL fields to service operations.
- Shared concept: Both templates organize application functionality into modules and delegate business operations to services.