fix: use 'name' for tasks/steps, fix resolver and test issues, ensure all server tests pass

This commit is contained in:
Sean Sube 2025-06-14 15:44:50 -05:00
parent 7e3b2a020c
commit 92cce945e9
No known key found for this signature in database
GPG Key ID: 3EED7B957D362AF1
17 changed files with 10794 additions and 0 deletions

31
server/jest.config.js Normal file
View File

@ -0,0 +1,31 @@
/** @type {import('jest').Config} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
testMatch: ['**/__tests__/**/*.test.ts'],
transform: {
'^.+\\.ts$': ['ts-jest', {
useESM: true,
}],
},
moduleFileExtensions: ['ts', 'js', 'json', 'node'],
setupFilesAfterEnv: ['<rootDir>/src/db/__tests__/setup.ts'],
extensionsToTreatAsEsm: ['.ts'],
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
},
collectCoverageFrom: [
'src/**/*.{ts,js}',
'!**/__tests__/**',
'!**/node_modules/**',
],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80,
},
},
};

8980
server/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

42
server/package.json Normal file
View File

@ -0,0 +1,42 @@
{
"name": "task-receipts-server",
"version": "1.0.0",
"description": "Task Receipts Server",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "ts-node-dev --respawn --transpile-only src/index.ts",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"lint": "eslint . --ext .ts",
"lint:fix": "eslint . --ext .ts --fix",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@apollo/server": "^4.10.0",
"@task-receipts/shared": "file:../shared",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.3",
"graphql": "^16.8.1",
"knex": "^3.1.0",
"pg": "^8.11.3",
"sqlite3": "^5.1.7"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/jest": "^29.5.12",
"@types/node": "^20.11.24",
"@types/pg": "^8.11.2",
"@typescript-eslint/eslint-plugin": "^7.1.0",
"@typescript-eslint/parser": "^7.1.0",
"eslint": "^8.57.0",
"jest": "^29.7.0",
"ts-jest": "^29.1.2",
"ts-node-dev": "^2.0.0",
"typescript": "^5.3.3"
}
}

View File

@ -0,0 +1,263 @@
import { testDb } from './setup.js';
import { groups, tasks, steps, images, users, notes, printHistory } from '../index.js';
import type { Group, Task, Step, Image, User, Note, PrintHistory } from '@shared/index';
describe('Database Operations', () => {
beforeEach(async () => {
// Clean up the database before each test
await images(testDb).delete();
await steps(testDb).delete();
await tasks(testDb).delete();
await groups(testDb).delete();
await users(testDb).delete();
await notes(testDb).delete();
await printHistory(testDb).delete();
});
afterAll(async () => {
// Close the database connection after all tests
await testDb.destroy();
});
describe('Groups', () => {
it('should create and retrieve a group', async () => {
const groupData: Omit<Group, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Group',
};
const [id] = await groups(testDb).insert(groupData);
const group = await groups(testDb).where({ id }).first();
expect(group).toBeDefined();
expect(group?.name).toBe(groupData.name);
});
it('should create a nested group', async () => {
const parentGroupData: Omit<Group, 'id' | 'created_at' | 'updated_at'> = {
name: 'Parent Group',
};
const [parentId] = await groups(testDb).insert(parentGroupData);
const childGroupData: Omit<Group, 'id' | 'created_at' | 'updated_at'> = {
name: 'Child Group',
};
const [childId] = await groups(testDb).insert(childGroupData);
const childGroup = await groups(testDb).where({ id: childId }).first();
expect(childGroup).toBeDefined();
expect(childGroup?.name).toBe(childGroupData.name);
});
});
describe('Tasks', () => {
it('should create and retrieve a task', async () => {
const groupData: Omit<Group, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Group',
};
const [groupId] = await groups(testDb).insert(groupData);
const taskData: Omit<Task, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Task',
group_id: groupId,
print_count: 0,
last_printed_at: undefined,
};
const [id] = await tasks(testDb).insert(taskData);
const task = await tasks(testDb).where({ id }).first();
expect(task).toBeDefined();
expect(task?.name).toBe(taskData.name);
expect(task?.group_id).toBe(groupId);
});
});
describe('Steps', () => {
it('should create and retrieve a step', async () => {
const groupData: Omit<Group, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Group',
};
const [groupId] = await groups(testDb).insert(groupData);
const taskData: Omit<Task, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Task',
group_id: groupId,
print_count: 0,
last_printed_at: undefined,
};
const [taskId] = await tasks(testDb).insert(taskData);
const stepData: Omit<Step, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Step',
instructions: 'Test Description',
task_id: taskId,
order: 1,
print_count: 0,
last_printed_at: undefined,
};
const [id] = await steps(testDb).insert(stepData);
const step = await steps(testDb).where({ id }).first();
expect(step).toBeDefined();
expect(step?.name).toBe(stepData.name);
expect(step?.instructions).toBe(stepData.instructions);
expect(step?.task_id).toBe(taskId);
});
});
describe('Images', () => {
it('should create and retrieve an image', async () => {
const groupData: Omit<Group, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Group',
};
const [groupId] = await groups(testDb).insert(groupData);
const taskData: Omit<Task, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Task',
group_id: groupId,
print_count: 0,
last_printed_at: undefined,
};
const [taskId] = await tasks(testDb).insert(taskData);
const stepData: Omit<Step, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Step',
instructions: 'Test Description',
task_id: taskId,
order: 1,
print_count: 0,
last_printed_at: undefined,
};
const [stepId] = await steps(testDb).insert(stepData);
const imageData: Omit<Image, 'id' | 'created_at' | 'updated_at'> = {
step_id: stepId,
original_path: '/path/to/image.png',
bw_path: '/path/to/image.bw.png',
order: 1,
};
const [id] = await images(testDb).insert(imageData);
const image = await images(testDb).where({ id }).first();
expect(image).toBeDefined();
expect(image?.step_id).toBe(stepId);
expect(image?.original_path).toBe(imageData.original_path);
expect(image?.bw_path).toBe(imageData.bw_path);
expect(image?.order).toBe(imageData.order);
});
});
describe('Users', () => {
it('should create and retrieve a user', async () => {
const userData: Omit<User, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test User',
};
const [id] = await users(testDb).insert(userData);
const user = await users(testDb).where({ id }).first();
expect(user).toBeDefined();
expect(user?.name).toBe(userData.name);
});
});
describe('Notes', () => {
it('should create and retrieve a note for a step', async () => {
const groupData: Omit<Group, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Group',
};
const [groupId] = await groups(testDb).insert(groupData);
const taskData: Omit<Task, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Task',
group_id: groupId,
print_count: 0,
last_printed_at: undefined,
};
const [taskId] = await tasks(testDb).insert(taskData);
const stepData: Omit<Step, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Step',
instructions: 'Test Description',
task_id: taskId,
order: 1,
print_count: 0,
last_printed_at: undefined,
};
const [stepId] = await steps(testDb).insert(stepData);
const userData: Omit<User, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test User',
};
const [userId] = await users(testDb).insert(userData);
const noteData: Omit<Note, 'id' | 'created_at' | 'updated_at'> = {
content: 'Test note for step',
step_id: stepId,
created_by: userId,
task_id: undefined,
};
const [id] = await notes(testDb).insert(noteData);
const note = await notes(testDb).where({ id }).first();
expect(note).toBeDefined();
expect(note?.content).toBe(noteData.content);
expect(note?.step_id).toBe(stepId);
expect(note?.created_by).toBe(userId);
expect(note?.task_id == null).toBe(true);
});
});
describe('PrintHistory', () => {
it('should create and retrieve a print history record for a task', async () => {
const groupData: Omit<Group, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Group',
};
const [groupId] = await groups(testDb).insert(groupData);
const taskData: Omit<Task, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test Task',
group_id: groupId,
print_count: 0,
last_printed_at: undefined,
};
const [taskId] = await tasks(testDb).insert(taskData);
const userData: Omit<User, 'id' | 'created_at' | 'updated_at'> = {
name: 'Test User',
};
const [userId] = await users(testDb).insert(userData);
const printHistoryData: Omit<PrintHistory, 'id' | 'created_at' | 'updated_at'> = {
task_id: taskId,
user_id: userId,
printed_at: new Date(),
};
const [id] = await printHistory(testDb).insert(printHistoryData);
const record = await printHistory(testDb).where({ id }).first();
expect(record).toBeDefined();
expect(record?.task_id).toBe(taskId);
expect(record?.user_id).toBe(userId);
});
});
});

View File

@ -0,0 +1,16 @@
import knex from 'knex';
import config from '../../db/knexfile.js';
export const testDb = knex(config.test);
beforeAll(async () => {
// Rollback all migrations first to ensure a clean state
await testDb.migrate.rollback();
// Run migrations
await testDb.migrate.latest();
});
afterAll(async () => {
// Close the database connection
await testDb.destroy();
});

35
server/src/db/index.ts Normal file
View File

@ -0,0 +1,35 @@
import knex, { Knex } from 'knex';
import config from './knexfile.js';
import type { Group, Task, Step, Image, User, Note, PrintHistory } from './types.js';
export function createDb(env: string = process.env.NODE_ENV || 'development') {
return knex(config[env]);
}
export function groups(db: Knex) {
return db<Group>('groups');
}
export function tasks(db: Knex) {
return db<Task>('tasks');
}
export function steps(db: Knex) {
return db<Step>('steps');
}
export function images(db: Knex) {
return db<Image>('images');
}
export function users(db: Knex) {
return db<User>('users');
}
export function notes(db: Knex) {
return db<Note>('notes');
}
export function printHistory(db: Knex) {
return db<PrintHistory>('print_history');
}

36
server/src/db/knexfile.ts Normal file
View File

@ -0,0 +1,36 @@
import type { Knex } from 'knex';
const config: { [key: string]: Knex.Config } = {
development: {
client: 'sqlite3',
connection: {
filename: './dev.sqlite3'
},
useNullAsDefault: true,
migrations: {
directory: './src/db/migrations'
}
},
test: {
client: 'sqlite3',
connection: {
filename: ':memory:'
},
useNullAsDefault: true,
migrations: {
directory: './src/db/migrations'
}
},
production: {
client: 'sqlite3',
connection: {
filename: './prod.sqlite3'
},
useNullAsDefault: true,
migrations: {
directory: './src/db/migrations'
}
}
};
export default config;

View File

@ -0,0 +1,80 @@
import type { Knex } from 'knex';
export async function up(knex: Knex): Promise<void> {
// Create groups table
await knex.schema.createTable('groups', (table) => {
table.increments('id').primary();
table.string('name').notNullable();
table.integer('parent_id').references('id').inTable('groups');
table.timestamps(true, true);
});
// Create tasks table
await knex.schema.createTable('tasks', (table) => {
table.increments('id').primary();
table.string('name').notNullable();
table.integer('group_id').references('id').inTable('groups').notNullable();
table.integer('print_count').defaultTo(0);
table.timestamp('last_printed_at');
table.timestamps(true, true);
});
// Create steps table
await knex.schema.createTable('steps', (table) => {
table.increments('id').primary();
table.string('name').notNullable();
table.text('instructions').notNullable();
table.integer('task_id').references('id').inTable('tasks').notNullable();
table.integer('order').notNullable();
table.integer('print_count').defaultTo(0);
table.timestamp('last_printed_at');
table.timestamps(true, true);
});
// Create images table for step images
await knex.schema.createTable('images', (table) => {
table.increments('id').primary();
table.integer('step_id').references('id').inTable('steps').notNullable();
table.string('original_path').notNullable();
table.string('bw_path').notNullable();
table.integer('order').notNullable();
table.timestamps(true, true);
});
// Create users table
await knex.schema.createTable('users', (table) => {
table.increments('id').primary();
table.string('name').notNullable();
table.timestamps(true, true);
});
// Create notes table
await knex.schema.createTable('notes', (table) => {
table.increments('id').primary();
table.text('content').notNullable();
table.integer('task_id').references('id').inTable('tasks');
table.integer('step_id').references('id').inTable('steps');
table.integer('created_by').references('id').inTable('users').notNullable();
table.timestamps(true, true);
});
// Create print history table
await knex.schema.createTable('print_history', (table) => {
table.increments('id').primary();
table.integer('user_id').references('id').inTable('users').notNullable();
table.integer('task_id').references('id').inTable('tasks');
table.integer('step_id').references('id').inTable('steps');
table.timestamp('printed_at').notNullable();
table.timestamps(true, true);
});
}
export async function down(knex: Knex): Promise<void> {
await knex.schema.dropTable('print_history');
await knex.schema.dropTable('notes');
await knex.schema.dropTable('users');
await knex.schema.dropTable('images');
await knex.schema.dropTable('steps');
await knex.schema.dropTable('tasks');
await knex.schema.dropTable('groups');
}

3
server/src/db/types.ts Normal file
View File

@ -0,0 +1,3 @@
import { Database, Group, Task, Step, Image, User, Note, PrintHistory } from '@shared/index';
export type { Database, Group, Task, Step, Image, User, Note, PrintHistory };

View File

@ -0,0 +1,763 @@
import { jest } from '@jest/globals';
import { Knex } from 'knex';
import { testDb } from '../../db/__tests__/setup';
import { resolvers } from '../resolvers';
import { groups, tasks, steps, images, users, notes, printHistory } from '../../db';
import type { Printer, Task, Step } from '@shared/index';
describe('GraphQL Resolvers', () => {
const context = {
db: testDb,
printer: {
printTask: jest.fn(),
printStep: jest.fn(),
} as unknown as Printer,
};
beforeEach(async () => {
await testDb('print_history').del();
await testDb('notes').del();
await testDb('images').del();
await testDb('steps').del();
await testDb('tasks').del();
await testDb('groups').del();
await testDb('users').del();
});
describe('Queries', () => {
describe('groups', () => {
it('should return all groups', async () => {
await groups(testDb).insert([
{ name: 'Group 1' },
{ name: 'Group 2' },
]);
const result = await resolvers.Query.groups(null, null, context);
expect(result).toHaveLength(2);
expect(result[0]?.name).toBe('Group 1');
expect(result[1]?.name).toBe('Group 2');
});
});
describe('group', () => {
it('should return a group by id', async () => {
const [id] = await groups(testDb).insert({ name: 'Test Group' });
const result = await resolvers.Query.group(null, { id: id.toString() }, context);
expect(result?.name).toBe('Test Group');
});
it('should return null for non-existent group', async () => {
const result = await resolvers.Query.group(null, { id: '999' }, context);
expect(result).toBeNull();
});
});
describe('tasks', () => {
it('should return tasks for a group', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
await tasks(testDb).insert([
{ name: 'Task 1', group_id: groupId },
{ name: 'Task 2', group_id: groupId },
]);
const result = await resolvers.Query.tasks(null, { groupId: groupId.toString() }, context);
expect(result).toHaveLength(2);
expect(result[0]?.name).toBe('Task 1');
expect(result[1]?.name).toBe('Task 2');
});
});
describe('task', () => {
it('should return a task by id', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const result = await resolvers.Query.task(null, { id: taskId.toString() }, context);
expect(result?.name).toBe('Test Task');
});
it('should return null for non-existent task', async () => {
const result = await resolvers.Query.task(null, { id: '999' }, context);
expect(result).toBeNull();
});
});
describe('steps', () => {
it('should return steps for a task', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
await steps(testDb).insert([
{ name: 'Step 1', instructions: 'Instructions 1', task_id: taskId, order: 1 },
{ name: 'Step 2', instructions: 'Instructions 2', task_id: taskId, order: 2 },
]);
const result = await resolvers.Query.steps(null, { taskId: taskId.toString() }, context);
expect(result).toHaveLength(2);
expect(result[0]?.name).toBe('Step 1');
expect(result[1]?.name).toBe('Step 2');
});
});
describe('step', () => {
it('should return a step by id', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [stepId] = await steps(testDb).insert({
name: 'Test Step',
instructions: 'Test Instructions',
task_id: taskId,
order: 1,
});
const result = await resolvers.Query.step(null, { id: stepId.toString() }, context);
expect(result?.name).toBe('Test Step');
});
it('should return null for non-existent step', async () => {
const result = await resolvers.Query.step(null, { id: '999' }, context);
expect(result).toBeNull();
});
});
describe('notes', () => {
it('should return notes for a task', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [userId] = await users(testDb).insert({ name: 'Test User' });
await notes(testDb).insert([
{ content: 'Note 1', task_id: taskId, created_by: userId },
{ content: 'Note 2', task_id: taskId, created_by: userId },
]);
const result = await resolvers.Query.notes(null, { taskId: taskId.toString() }, context);
expect(result).toHaveLength(2);
expect(result[0]?.content).toBe('Note 1');
expect(result[1]?.content).toBe('Note 2');
});
it('should return notes for a step', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [stepId] = await steps(testDb).insert({
name: 'Test Step',
instructions: 'Test Instructions',
task_id: taskId,
order: 1,
});
const [userId] = await users(testDb).insert({ name: 'Test User' });
await notes(testDb).insert([
{ content: 'Note 1', step_id: stepId, created_by: userId },
{ content: 'Note 2', step_id: stepId, created_by: userId },
]);
const result = await resolvers.Query.notes(null, { stepId: stepId.toString() }, context);
expect(result).toHaveLength(2);
expect(result[0]?.content).toBe('Note 1');
expect(result[1]?.content).toBe('Note 2');
});
it('should return empty array for non-existent task', async () => {
const result = await resolvers.Query.notes(null, { taskId: '999' }, context);
expect(result).toHaveLength(0);
});
it('should return empty array for non-existent step', async () => {
const result = await resolvers.Query.notes(null, { stepId: '999' }, context);
expect(result).toHaveLength(0);
});
});
describe('printHistory', () => {
it('should return print history for a task', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [userId] = await users(testDb).insert({ name: 'Test User' });
await printHistory(testDb).insert([
{
user_id: userId,
task_id: taskId,
printed_at: new Date(),
},
{
user_id: userId,
task_id: taskId,
printed_at: new Date(),
},
]);
const result = await resolvers.Query.printHistory(null, { taskId: taskId.toString() }, context);
expect(result).toHaveLength(2);
});
it('should return print history for a step', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [stepId] = await steps(testDb).insert({
name: 'Test Step',
instructions: 'Test Instructions',
task_id: taskId,
order: 1,
});
const [userId] = await users(testDb).insert({ name: 'Test User' });
await printHistory(testDb).insert([
{
user_id: userId,
step_id: stepId,
printed_at: new Date(),
},
{
user_id: userId,
step_id: stepId,
printed_at: new Date(),
},
]);
const result = await resolvers.Query.printHistory(null, { stepId: stepId.toString() }, context);
expect(result).toHaveLength(2);
});
it('should return empty array for non-existent task', async () => {
const result = await resolvers.Query.printHistory(null, { taskId: '999' }, context);
expect(result).toHaveLength(0);
});
it('should return empty array for non-existent step', async () => {
const result = await resolvers.Query.printHistory(null, { stepId: '999' }, context);
expect(result).toHaveLength(0);
});
});
});
describe('Mutations', () => {
describe('createGroup', () => {
it('should create a group', async () => {
const result = await resolvers.Mutation.createGroup(null, { name: 'Test Group' }, context);
expect(result?.name).toBe('Test Group');
});
it('should create a group with parent', async () => {
const [parentId] = await groups(testDb).insert({ name: 'Parent Group' });
const result = await resolvers.Mutation.createGroup(
null,
{ name: 'Child Group', parentId: parentId.toString() },
context
);
expect(result?.name).toBe('Child Group');
expect(result?.parent_id).toBe(parentId);
});
it('should throw error for non-existent parent', async () => {
await expect(
resolvers.Mutation.createGroup(null, { name: 'Child Group', parentId: '999' }, context)
).rejects.toThrow('Parent group not found');
});
});
describe('createTask', () => {
it('should create a task', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const result = await resolvers.Mutation.createTask(
null,
{ name: 'Test Task', groupId: groupId.toString() },
context
);
expect(result?.name).toBe('Test Task');
});
it('should throw error for non-existent group', async () => {
await expect(
resolvers.Mutation.createTask(null, { name: 'Test Task', groupId: '999' }, context)
).rejects.toThrow('Group not found');
});
});
describe('createStep', () => {
it('should create a step', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const result = await resolvers.Mutation.createStep(
null,
{
name: 'Test Step',
instructions: 'Test Instructions',
taskId: taskId.toString(),
order: 1,
},
context
);
expect(result?.name).toBe('Test Step');
});
it('should throw error for non-existent task', async () => {
await expect(
resolvers.Mutation.createStep(
null,
{
name: 'Test Step',
instructions: 'Test Instructions',
taskId: '999',
order: 1,
},
context
)
).rejects.toThrow('Task not found');
});
});
describe('createImage', () => {
it('should create an image', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [stepId] = await steps(testDb).insert({
name: 'Test Step',
instructions: 'Test Instructions',
task_id: taskId,
order: 1,
});
const result = await resolvers.Mutation.createImage(
null,
{
stepId: stepId.toString(),
originalPath: '/path/to/image.jpg',
bwPath: '/path/to/image.jpg',
order: 1,
},
context
);
expect(result?.original_path).toBe('/path/to/image.jpg');
expect(result?.bw_path).toBe('/path/to/image.jpg');
});
it('should throw error for non-existent step', async () => {
await expect(
resolvers.Mutation.createImage(
null,
{
stepId: '999',
originalPath: '/path/to/image.jpg',
bwPath: '/path/to/image.jpg',
order: 1,
},
context
)
).rejects.toThrow('Step not found');
});
});
describe('createNote', () => {
it('should create a note for a task', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [userId] = await users(testDb).insert({ name: 'Test User' });
const result = await resolvers.Mutation.createNote(
null,
{
content: 'Test Note',
taskId: taskId.toString(),
userId: userId.toString(),
},
context
);
expect(result?.content).toBe('Test Note');
expect(result?.task_id).toBe(taskId);
expect(result?.created_by).toBe(userId);
});
it('should create a note for a step', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [stepId] = await steps(testDb).insert({
name: 'Test Step',
instructions: 'Test Instructions',
task_id: taskId,
order: 1,
});
const [userId] = await users(testDb).insert({ name: 'Test User' });
const result = await resolvers.Mutation.createNote(
null,
{
content: 'Test Note',
stepId: stepId.toString(),
userId: userId.toString(),
},
context
);
expect(result?.content).toBe('Test Note');
expect(result?.step_id).toBe(stepId);
expect(result?.created_by).toBe(userId);
});
it('should throw error for non-existent task', async () => {
const [userId] = await users(testDb).insert({ name: 'Test User' });
await expect(
resolvers.Mutation.createNote(
null,
{
content: 'Test Note',
taskId: '999',
userId: userId.toString(),
},
context
)
).rejects.toThrow('Task not found');
});
it('should throw error for non-existent step', async () => {
const [userId] = await users(testDb).insert({ name: 'Test User' });
await expect(
resolvers.Mutation.createNote(
null,
{
content: 'Test Note',
stepId: '999',
userId: userId.toString(),
},
context
)
).rejects.toThrow('Step not found');
});
it('should throw error for non-existent user', async () => {
await expect(
resolvers.Mutation.createNote(
null,
{
content: 'Test Note',
userId: '999',
},
context
)
).rejects.toThrow('User not found');
});
});
describe('printTask', () => {
it('should print a task', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [userId] = await users(testDb).insert({ name: 'Test User' });
const result = await resolvers.Mutation.printTask(
null,
{ id: taskId.toString(), userId: userId.toString() },
context
);
expect(result?.print_count).toBe(1);
expect(result?.last_printed_at).toBeDefined();
expect(context.printer.printTask).toHaveBeenCalled();
});
it('should throw error for non-existent task', async () => {
const [userId] = await users(testDb).insert({ name: 'Test User' });
await expect(
resolvers.Mutation.printTask(null, { id: '999', userId: userId.toString() }, context)
).rejects.toThrow('Task not found');
});
it('should throw error for non-existent user', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
await expect(
resolvers.Mutation.printTask(null, { id: taskId.toString(), userId: '999' }, context)
).rejects.toThrow('User not found');
});
});
describe('printStep', () => {
it('should print a step', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [stepId] = await steps(testDb).insert({
name: 'Test Step',
instructions: 'Test Instructions',
task_id: taskId,
order: 1,
});
const [userId] = await users(testDb).insert({ name: 'Test User' });
const result = await resolvers.Mutation.printStep(
null,
{ id: stepId.toString(), userId: userId.toString() },
context
);
expect(result?.print_count).toBe(1);
expect(result?.last_printed_at).toBeDefined();
expect(context.printer.printStep).toHaveBeenCalled();
});
it('should throw error for non-existent step', async () => {
const [userId] = await users(testDb).insert({ name: 'Test User' });
await expect(
resolvers.Mutation.printStep(null, { id: '999', userId: userId.toString() }, context)
).rejects.toThrow('Step not found');
});
it('should throw error for non-existent user', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [stepId] = await steps(testDb).insert({
name: 'Test Step',
instructions: 'Test Instructions',
task_id: taskId,
order: 1,
});
await expect(
resolvers.Mutation.printStep(null, { id: stepId.toString(), userId: '999' }, context)
).rejects.toThrow('User not found');
});
});
});
describe('Field Resolvers', () => {
describe('Group', () => {
it('should resolve tasks field', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
await tasks(testDb).insert([
{ name: 'Task 1', group_id: groupId },
{ name: 'Task 2', group_id: groupId },
]);
const group = await groups(testDb).where('id', groupId).first();
if (!group) throw new Error('Group not found');
const result = await resolvers.Group.tasks(group, null, context);
expect(result).toHaveLength(2);
expect(result[0]?.name).toBe('Task 1');
expect(result[1]?.name).toBe('Task 2');
});
});
describe('Task', () => {
it('should resolve group field', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const task = await tasks(testDb).where('id', taskId).first();
if (!task) throw new Error('Task not found');
const result = await resolvers.Task.group(task, null, context);
expect(result?.name).toBe('Test Group');
});
it('should resolve steps field', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
await steps(testDb).insert([
{ name: 'Step 1', instructions: 'Instructions 1', task_id: taskId, order: 1 },
{ name: 'Step 2', instructions: 'Instructions 2', task_id: taskId, order: 2 },
]);
const task = await tasks(testDb).where('id', taskId).first();
if (!task) throw new Error('Task not found');
const result = await resolvers.Task.steps(task, null, context);
expect(result).toHaveLength(2);
expect(result[0]?.name).toBe('Step 1');
expect(result[1]?.name).toBe('Step 2');
});
it('should resolve notes field', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [userId] = await users(testDb).insert({ name: 'Test User' });
await notes(testDb).insert([
{ content: 'Note 1', task_id: taskId, created_by: userId },
{ content: 'Note 2', task_id: taskId, created_by: userId },
]);
const task = await tasks(testDb).where('id', taskId).first();
if (!task) throw new Error('Task not found');
const result = await resolvers.Task.notes(task, null, context);
expect(result).toHaveLength(2);
expect(result[0]?.content).toBe('Note 1');
expect(result[1]?.content).toBe('Note 2');
});
it('should resolve printHistory field', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [userId] = await users(testDb).insert({ name: 'Test User' });
await printHistory(testDb).insert([
{
user_id: userId,
task_id: taskId,
printed_at: new Date(),
},
{
user_id: userId,
task_id: taskId,
printed_at: new Date(),
},
]);
const task = await tasks(testDb).where('id', taskId).first();
if (!task) throw new Error('Task not found');
const result = await resolvers.Task.printHistory(task, null, context);
expect(result).toHaveLength(2);
});
});
describe('Step', () => {
it('should resolve task field', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [stepId] = await steps(testDb).insert({
name: 'Test Step',
instructions: 'Test Instructions',
task_id: taskId,
order: 1,
});
const step = await steps(testDb).where('id', stepId).first();
if (!step) throw new Error('Step not found');
const result = await resolvers.Step.task(step, null, context);
expect(result?.name).toBe('Test Task');
});
it('should resolve images field', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [stepId] = await steps(testDb).insert({
name: 'Test Step',
instructions: 'Test Instructions',
task_id: taskId,
order: 1,
});
await images(testDb).insert([
{
step_id: stepId,
original_path: '/path/to/original1.jpg',
bw_path: '/path/to/bw1.jpg',
order: 1,
},
{
step_id: stepId,
original_path: '/path/to/original2.jpg',
bw_path: '/path/to/bw2.jpg',
order: 2,
},
]);
const step = await steps(testDb).where('id', stepId).first();
if (!step) throw new Error('Step not found');
const result = await resolvers.Step.images(step, null, context);
expect(result).toHaveLength(2);
expect(result[0]?.original_path).toBe('/path/to/original1.jpg');
expect(result[1]?.original_path).toBe('/path/to/original2.jpg');
});
it('should resolve notes field', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [stepId] = await steps(testDb).insert({
name: 'Test Step',
instructions: 'Test Instructions',
task_id: taskId,
order: 1,
});
const [userId] = await users(testDb).insert({ name: 'Test User' });
await notes(testDb).insert([
{ content: 'Note 1', step_id: stepId, created_by: userId },
{ content: 'Note 2', step_id: stepId, created_by: userId },
]);
const step = await steps(testDb).where('id', stepId).first();
if (!step) throw new Error('Step not found');
const result = await resolvers.Step.notes(step, null, context);
expect(result).toHaveLength(2);
expect(result[0]?.content).toBe('Note 1');
expect(result[1]?.content).toBe('Note 2');
});
it('should resolve printHistory field', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [stepId] = await steps(testDb).insert({
name: 'Test Step',
instructions: 'Test Instructions',
task_id: taskId,
order: 1,
});
const [userId] = await users(testDb).insert({ name: 'Test User' });
await printHistory(testDb).insert({
user_id: userId,
step_id: stepId,
printed_at: new Date(),
});
const history = await printHistory(testDb).where('step_id', stepId).first();
if (!history) throw new Error('Print history not found');
const result = await resolvers.PrintHistory.step(history, null, context);
expect(result?.name).toBe('Test Step');
});
});
describe('Note', () => {
it('should resolve createdBy field', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [userId] = await users(testDb).insert({ name: 'Test User' });
await notes(testDb).insert({
content: 'Test Note',
task_id: taskId,
created_by: userId,
});
const note = await notes(testDb).where('task_id', taskId).first();
if (!note) throw new Error('Note not found');
const result = await resolvers.Note.createdBy(note, null, context);
expect(result?.name).toBe('Test User');
});
});
describe('PrintHistory', () => {
it('should resolve user field', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [userId] = await users(testDb).insert({ name: 'Test User' });
await printHistory(testDb).insert({
user_id: userId,
task_id: taskId,
printed_at: new Date(),
});
const history = await printHistory(testDb).where('task_id', taskId).first();
if (!history) throw new Error('Print history not found');
const result = await resolvers.PrintHistory.user(history, null, context);
expect(result?.name).toBe('Test User');
});
it('should resolve task field', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [userId] = await users(testDb).insert({ name: 'Test User' });
await printHistory(testDb).insert({
user_id: userId,
task_id: taskId,
printed_at: new Date(),
});
const history = await printHistory(testDb).where('task_id', taskId).first();
if (!history) throw new Error('Print history not found');
const result = await resolvers.PrintHistory.task(history, null, context);
expect(result?.name).toBe('Test Task');
});
it('should resolve step field', async () => {
const [groupId] = await groups(testDb).insert({ name: 'Test Group' });
const [taskId] = await tasks(testDb).insert({ name: 'Test Task', group_id: groupId });
const [stepId] = await steps(testDb).insert({
name: 'Test Step',
instructions: 'Test Instructions',
task_id: taskId,
order: 1,
});
const [userId] = await users(testDb).insert({ name: 'Test User' });
await printHistory(testDb).insert({
user_id: userId,
step_id: stepId,
printed_at: new Date(),
});
const history = await printHistory(testDb).where('step_id', stepId).first();
if (!history) throw new Error('Print history not found');
const result = await resolvers.PrintHistory.step(history, null, context);
expect(result?.name).toBe('Test Step');
});
});
});
});

View File

@ -0,0 +1,247 @@
import { Knex } from 'knex';
import { groups, tasks, steps, images, users, notes, printHistory } from '../db';
import type { Printer } from '@shared/index';
interface Context {
db: Knex;
printer: Printer;
}
export const resolvers = {
Query: {
groups: async (_: any, __: any, { db }: Context) => {
return await groups(db).select('*');
},
group: async (_: any, { id }: { id: string }, { db }: Context) => {
const group = await groups(db).where('id', id).first();
return group || null;
},
tasks: async (_: any, { groupId }: { groupId: string }, { db }: Context) => {
return await tasks(db).where('group_id', groupId).select('*');
},
task: async (_: any, { id }: { id: string }, { db }: Context) => {
const task = await tasks(db).where('id', id).first();
return task || null;
},
steps: async (_: any, { taskId }: { taskId: string }, { db }: Context) => {
return await steps(db).where('task_id', taskId).orderBy('order').select('*');
},
step: async (_: any, { id }: { id: string }, { db }: Context) => {
const step = await steps(db).where('id', id).first();
return step || null;
},
recentTasks: async (_: any, __: any, { db }: Context) => {
return await tasks(db)
.orderBy('created_at', 'desc')
.limit(10)
.select('*');
},
frequentTasks: async (_: any, __: any, { db }: Context) => {
return await tasks(db)
.orderBy('created_at', 'desc')
.limit(10)
.select('*');
},
users: async (_: any, __: any, { db }: Context) => {
return await users(db).select('*');
},
user: async (_: any, { id }: { id: string }, { db }: Context) => {
const user = await users(db).where('id', id).first();
return user || null;
},
notes: async (_: any, { stepId, taskId }: { stepId?: string; taskId?: string }, { db }: Context) => {
const query = notes(db);
if (stepId) {
query.where('step_id', stepId);
}
if (taskId) {
query.where('task_id', taskId);
}
return await query.select('*');
},
printHistory: async (_: any, { taskId, stepId }: { taskId?: string; stepId?: string }, { db }: Context) => {
const query = printHistory(db);
if (taskId) {
query.where('task_id', taskId);
}
if (stepId) {
query.where('step_id', stepId);
}
return await query.select('*');
},
},
Mutation: {
createGroup: async (_: any, { name, parentId }: { name: string; parentId?: string }, { db }: Context) => {
let parent_id: number | undefined = undefined;
if (parentId) {
const parent = await groups(db).where('id', parentId).first();
if (!parent) throw new Error('Parent group not found');
parent_id = parseInt(parentId);
}
const [id] = await groups(db).insert({ name, parent_id });
return await groups(db).where('id', id).first();
},
createTask: async (_: any, { name, groupId }: { name: string; groupId: string }, { db }: Context) => {
const group = await groups(db).where('id', groupId).first();
if (!group) throw new Error('Group not found');
const [id] = await tasks(db).insert({
name,
group_id: parseInt(groupId),
print_count: 0,
});
return await tasks(db).where('id', id).first();
},
createStep: async (_: any, { name, instructions, taskId, order }: { name: string; instructions: string; taskId: string; order: number }, { db }: Context) => {
const task = await tasks(db).where('id', taskId).first();
if (!task) throw new Error('Task not found');
const [id] = await steps(db).insert({
name,
instructions,
task_id: parseInt(taskId),
order,
print_count: 0,
});
return await steps(db).where('id', id).first();
},
createImage: async (_: any, { stepId, originalPath, bwPath, order }: { stepId: string; originalPath: string; bwPath: string; order: number }, { db }: Context) => {
const step = await steps(db).where('id', stepId).first();
if (!step) throw new Error('Step not found');
const [id] = await images(db).insert({
step_id: parseInt(stepId),
original_path: originalPath,
bw_path: bwPath,
order,
});
return await images(db).where('id', id).first();
},
createUser: async (_: any, { name }: { name: string }, { db }: Context) => {
const [id] = await users(db).insert({ name });
return await users(db).where('id', id).first();
},
createNote: async (
_: any,
{ content, stepId, taskId, userId }: { content: string; stepId?: string; taskId?: string; userId: string },
{ db }: Context
) => {
const user = await users(db).where('id', userId).first();
if (!user) throw new Error('User not found');
if (stepId) {
const step = await steps(db).where('id', stepId).first();
if (!step) throw new Error('Step not found');
} else if (taskId) {
const task = await tasks(db).where('id', taskId).first();
if (!task) throw new Error('Task not found');
}
const [id] = await notes(db).insert({
content,
step_id: stepId ? parseInt(stepId) : undefined,
task_id: taskId ? parseInt(taskId) : undefined,
created_by: parseInt(userId),
});
return await notes(db).where('id', id).first();
},
printTask: async (_: any, { id, userId }: { id: string; userId: string }, { db, printer }: Context) => {
const task = await tasks(db).where('id', id).first();
if (!task) throw new Error('Task not found');
const user = await users(db).where('id', userId).first();
if (!user) throw new Error('User not found');
await printer.printTask(task, db);
await printHistory(db).insert({
user_id: parseInt(userId),
task_id: parseInt(id),
printed_at: new Date(),
created_at: new Date(),
updated_at: new Date(),
});
await tasks(db).where('id', id).update({
print_count: (task.print_count || 0) + 1,
last_printed_at: new Date(),
updated_at: new Date(),
});
return await tasks(db).where('id', id).first();
},
printStep: async (_: any, { id, userId }: { id: string; userId: string }, { db, printer }: Context) => {
const step = await steps(db).where('id', id).first();
if (!step) throw new Error('Step not found');
const user = await users(db).where('id', userId).first();
if (!user) throw new Error('User not found');
await printer.printStep(step, db);
await printHistory(db).insert({
user_id: parseInt(userId),
step_id: parseInt(id),
printed_at: new Date(),
created_at: new Date(),
updated_at: new Date(),
});
await steps(db).where('id', id).update({
print_count: (step.print_count || 0) + 1,
last_printed_at: new Date(),
updated_at: new Date(),
});
return await steps(db).where('id', id).first();
},
},
Group: {
tasks: async (group: { id: number }, _: any, { db }: Context) => {
return await tasks(db).where('group_id', group.id).select('*');
},
},
Task: {
group: async (task: { group_id: number }, _: any, { db }: Context) => {
const group = await groups(db).where('id', task.group_id).first();
return group || null;
},
steps: async (task: { id: number }, _: any, { db }: Context) => {
return await steps(db).where('task_id', task.id).orderBy('order').select('*');
},
notes: async (task: { id: number }, _: any, { db }: Context) => {
return await notes(db).where('task_id', task.id).select('*');
},
printHistory: async (task: { id: number }, _: any, { db }: Context) => {
return await printHistory(db).where('task_id', task.id).select('*');
},
},
Step: {
task: async (step: { task_id: number }, _: any, { db }: Context) => {
const task = await tasks(db).where('id', step.task_id).first();
return task || null;
},
images: async (step: { id: number }, _: any, { db }: Context) => {
return await images(db).where('step_id', step.id).orderBy('order').select('*');
},
notes: async (step: { id: number }, _: any, { db }: Context) => {
return await notes(db).where('step_id', step.id).select('*');
},
printHistory: async (step: { id: number }, _: any, { db }: Context) => {
return await printHistory(db).where('step_id', step.id).select('*');
},
},
Note: {
createdBy: async (note: { created_by: number }, _: any, { db }: Context) => {
const user = await users(db).where('id', note.created_by).first();
return user || null;
},
},
PrintHistory: {
user: async (history: { user_id: number }, _: any, { db }: Context) => {
const user = await users(db).where('id', history.user_id).first();
return user || null;
},
task: async (history: { task_id?: number }, _: any, { db }: Context) => {
if (!history.task_id) return null;
const task = await tasks(db).where('id', history.task_id).first();
return task || null;
},
step: async (history: { step_id?: number }, _: any, { db }: Context) => {
if (!history.step_id) return null;
const step = await steps(db).where('id', history.step_id).first();
return step || null;
},
},
};

View File

@ -0,0 +1,105 @@
import { gql } from 'graphql-tag';
export const typeDefs = gql`
type Group {
id: ID!
name: String!
parentId: ID
tasks: [Task!]!
createdAt: String!
updatedAt: String!
}
type Task {
id: ID!
name: String!
groupId: ID!
group: Group!
steps: [Step!]!
printCount: Int!
lastPrintedAt: String
createdAt: String!
updatedAt: String!
notes: [Note!]!
printHistory: [PrintHistory!]!
}
type Step {
id: ID!
name: String!
instructions: String!
taskId: ID!
task: Task!
order: Int!
images: [Image!]!
printCount: Int!
lastPrintedAt: String
createdAt: String!
updatedAt: String!
notes: [Note!]!
printHistory: [PrintHistory!]!
}
type Image {
id: ID!
stepId: ID!
originalPath: String!
bwPath: String!
order: Int!
createdAt: String!
updatedAt: String!
}
type User {
id: ID!
name: String!
createdAt: String!
updatedAt: String!
}
type Note {
id: ID!
content: String!
taskId: ID
stepId: ID
createdBy: User!
createdAt: String!
updatedAt: String!
}
type PrintHistory {
id: ID!
user: User!
task: Task
step: Step
printedAt: String!
createdAt: String!
updatedAt: String!
}
type Query {
groups: [Group!]!
group(id: ID!): Group
tasks(groupId: ID!): [Task!]!
task(id: ID!): Task
steps(taskId: ID!): [Step!]!
step(id: ID!): Step
recentTasks: [Task!]!
frequentTasks: [Task!]!
users: [User!]!
user(id: ID!): User
notes(taskId: ID, stepId: ID): [Note!]!
printHistory(taskId: ID, stepId: ID): [PrintHistory!]!
}
type Mutation {
createGroup(name: String!, parentId: ID): Group!
createTask(name: String!, groupId: ID!): Task!
createStep(name: String!, instructions: String!, taskId: ID!, order: Int!): Step!
createImage(stepId: ID!, originalPath: String!, bwPath: String!, order: Int!): Image!
createUser(name: String!): User!
createNote(content: String!, taskId: ID, stepId: ID, createdBy: ID!): Note!
printTask(id: ID!, userId: ID!): Task!
printStep(id: ID!, userId: ID!): Step!
}
`;

58
server/src/index.ts Normal file
View File

@ -0,0 +1,58 @@
import express from 'express';
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import { json } from 'body-parser';
import { typeDefs } from './graphql/schema';
import { resolvers } from './graphql/resolvers';
import { createDb } from './db';
import logger from './logger';
import { TestPrinter } from './printer';
const app = express();
const port = process.env.PORT || 4000;
async function startServer() {
const db = createDb();
const printer = new TestPrinter();
const server = new ApolloServer({
typeDefs,
resolvers,
});
await server.start();
app.use(json());
app.use(
'/graphql',
expressMiddleware(server, {
context: async () => ({ db, printer }),
})
);
const httpServer = app.listen(port, () => {
logger.info(`Server running at http://localhost:${port}/graphql`);
});
// Graceful shutdown
process.on('SIGTERM', () => {
logger.info('SIGTERM received. Shutting down gracefully...');
httpServer.close(() => {
logger.info('Server closed');
process.exit(0);
});
});
process.on('SIGINT', () => {
logger.info('SIGINT received. Shutting down gracefully...');
httpServer.close(() => {
logger.info('Server closed');
process.exit(0);
});
});
}
startServer().catch((error) => {
logger.error('Failed to start server:', error);
process.exit(1);
});

39
server/src/logger.ts Normal file
View File

@ -0,0 +1,39 @@
import winston from 'winston';
import path from 'path';
const logDir = path.join(process.cwd(), 'logs');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
// Write all logs to console
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
),
}),
// Write all logs with level 'error' and below to error.log
new winston.transports.File({
filename: path.join(logDir, 'error.log'),
level: 'error',
}),
// Write all logs with level 'info' and below to combined.log
new winston.transports.File({
filename: path.join(logDir, 'combined.log'),
}),
],
});
// Create a stream object for Morgan integration
export const stream = {
write: (message: string) => {
logger.info(message.trim());
},
};
export default logger;

View File

@ -0,0 +1,14 @@
import { Knex } from 'knex';
import { Task, Step, Printer } from '@shared/index';
import { TestPrinter } from './test-printer';
// This will be replaced with a real printer implementation later
const printer: Printer = new TestPrinter();
export async function printTask(task: Task, db: Knex): Promise<void> {
await printer.printTask(task, db);
}
export async function printStep(step: Step, db: Knex): Promise<void> {
await printer.printStep(step, db);
}

View File

@ -0,0 +1,65 @@
import fs from 'fs/promises';
import path from 'path';
import { Task, Step, Printer } from '@shared/index';
import { steps } from '../db';
import { Knex } from 'knex';
import logger from '../logger';
export class TestPrinter implements Printer {
private readonly outputDir: string;
constructor() {
this.outputDir = path.join(process.cwd(), 'test-output');
this.ensureOutputDir();
}
private async ensureOutputDir() {
try {
await fs.mkdir(this.outputDir, { recursive: true });
} catch (error) {
logger.error('Failed to create output directory:', error);
}
}
async getTaskSteps(db: Knex, task: Task): Promise<Step[]> {
return await steps(db).where('task_id', task.id).orderBy('order').select('*');
}
async printTask(task: Task, db: Knex): Promise<void> {
const taskSteps = await this.getTaskSteps(db, task);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = path.join(this.outputDir, `task-${task.id}-${timestamp}.txt`);
const content = [
`Task: ${task.name}`,
'='.repeat(40),
'',
...taskSteps.map((step, index) => [
`Step ${index + 1}: ${step.name}`,
'-'.repeat(40),
step.description ?? '',
'',
]).flat(),
].join('\n');
await fs.writeFile(filename, content);
logger.info(`Printed task ${task.id} to ${filename}`);
}
async printStep(step: Step, db: Knex): Promise<void> {
void db; // avoid unused parameter warning
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = path.join(this.outputDir, `step-${step.id}-${timestamp}.txt`);
const content = [
`Step: ${step.name}`,
'='.repeat(40),
'',
step.description ?? '',
'',
].join('\n');
await fs.writeFile(filename, content);
logger.info(`Printed step ${step.id} to ${filename}`);
}
}

17
server/tsconfig.json Normal file
View File

@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"paths": {
"@shared/*": ["../shared/types/*"]
}
},
"include": ["src/**/*", "../shared/types/**/*"],
"exclude": ["node_modules", "dist"]
}