Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 157 additions & 0 deletions apps/backend/src/anthology/anthology.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import { Test, TestingModule } from '@nestjs/testing';
import { NotFoundException } from '@nestjs/common';
import { AnthologyController } from './anthology.controller';
import { AnthologyService } from './anthology.service';
import { Anthology } from './anthology.entity';
import { Story } from '../story/story.entity';

// mock interceptor to avoid dependency injection issues
jest.mock('../interceptors/current-user.interceptor', () => ({
CurrentUserInterceptor: jest.fn().mockImplementation(() => ({
intercept: jest.fn((context, next) => next.handle()), // just passes through
})),
}));

describe('AnthologyController', () => {
let controller: AnthologyController;

const mockStory: Story = {
id: 1,
title: 'Test Story',
description: 'A story for testing',
author: 'Ala’a Tamam',
student_bio: 'Data Science student',
genre: 'Fiction',
theme: 'Hope',
anthology: { id: 1 } as Anthology,
};

const mockAnthology: Anthology = {
id: 1,
title: 'Test Anthology',
description: 'A test anthology',
published_year: 2024,
status: 'PUBLISHED' as unknown as Anthology['status'],
pub_level: 'PERFECT_BOUND' as unknown as Anthology['pub_level'],
programs: ['Test Program'],
inventory: 20,
photo_url: 'https://example.com/photo.jpg',
genre: 'Fiction',
theme: 'Resilience',
isbn: '1234567890',
shopify_url: 'https://shopify.com/test',
};

const mockAnthologyService = {
findOne: jest.fn(),
findAll: jest.fn(),
remove: jest.fn(),
getStories: jest.fn(),
};

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AnthologyController],
providers: [
{
provide: AnthologyService,
useValue: mockAnthologyService,
},
],
}).compile();

controller = module.get<AnthologyController>(AnthologyController);
});

afterEach(() => {
jest.clearAllMocks();
});

it('should be defined', () => {
expect(controller).toBeDefined();
});

describe('getAnthology', () => {
it('should return an anthology when found', async () => {
mockAnthologyService.findOne.mockResolvedValue(mockAnthology);

const result = await controller.getAnthology(1);

expect(result).toEqual(mockAnthology);
expect(mockAnthologyService.findOne).toHaveBeenCalledWith(1);
});

it('should return null when anthology not found', async () => {
mockAnthologyService.findOne.mockResolvedValue(null);

const result = await controller.getAnthology(999);

expect(result).toBeNull();
expect(mockAnthologyService.findOne).toHaveBeenCalledWith(999);
});
});

describe('getAllAnthologies', () => {
it('should return all anthologies', async () => {
mockAnthologyService.findAll.mockResolvedValue([mockAnthology]);

const result = await controller.getAllAnthologies();

expect(result).toEqual([mockAnthology]);
expect(mockAnthologyService.findAll).toHaveBeenCalled();
});
});

describe('getAnthologyStories', () => {
it('should return an array of stories when anthology exists', async () => {
mockAnthologyService.getStories.mockResolvedValue([mockStory]);

const result = await controller.getAnthologyStories(1);

expect(result).toEqual([mockStory]);
expect(mockAnthologyService.getStories).toHaveBeenCalledWith(1);
});

it('should return an empty array if no stories exist', async () => {
mockAnthologyService.getStories.mockResolvedValue([]);

const result = await controller.getAnthologyStories(1);

expect(result).toEqual([]);
expect(mockAnthologyService.getStories).toHaveBeenCalledWith(1);
});

it('should throw NotFoundException when anthology not found', async () => {
mockAnthologyService.getStories.mockRejectedValue(
new NotFoundException('Anthology not found'),
);

await expect(controller.getAnthologyStories(999)).rejects.toThrow(
NotFoundException,
);
expect(mockAnthologyService.getStories).toHaveBeenCalledWith(999);
});
});

describe('removeAnthology', () => {
it('should remove an anthology successfully', async () => {
mockAnthologyService.remove.mockResolvedValue(mockAnthology);

const result = await controller.removeAnthology(1);

expect(result).toEqual(mockAnthology);
expect(mockAnthologyService.remove).toHaveBeenCalledWith(1);
});

it('should throw NotFoundException when anthology not found', async () => {
mockAnthologyService.remove.mockRejectedValue(
new NotFoundException('Anthology not found'),
);

await expect(controller.removeAnthology(999)).rejects.toThrow(
NotFoundException,
);
expect(mockAnthologyService.remove).toHaveBeenCalledWith(999);
});
});
});
25 changes: 24 additions & 1 deletion apps/backend/src/anthology/anthology.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@ import { AnthologyService } from './anthology.service';
import { Anthology } from './anthology.entity';
import { AuthGuard } from '@nestjs/passport';
import { CurrentUserInterceptor } from '../interceptors/current-user.interceptor';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import {
ApiBearerAuth,
ApiTags,
ApiOperation,
ApiResponse,
} from '@nestjs/swagger';
import { Story } from '../story/story.entity';

@ApiTags('Anthologies')
@ApiBearerAuth()
Expand Down Expand Up @@ -39,4 +45,21 @@ export class AnthologyController {
): Promise<Anthology> {
return this.anthologyService.remove(id);
}

@Get('/:id/stories')
@ApiOperation({ summary: 'Get all stories for a specific anthology' })
@ApiResponse({
status: 200,
description: 'Stories retrieved successfully',
type: [Story],
})
@ApiResponse({
status: 404,
description: 'Anthology not found',
})
async getAnthologyStories(
@Param('id', ParseIntPipe) id: number,
): Promise<Story[]> {
return this.anthologyService.getStories(id);
}
}
7 changes: 5 additions & 2 deletions apps/backend/src/anthology/anthology.entity.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Entity, Column, IntegerType } from 'typeorm';

import { Entity, Column, IntegerType, OneToMany } from 'typeorm';
import { Story } from '../story/story.entity';
import { AnthologyStatus, AnthologyPubLevel } from './types';

@Entity()
Expand Down Expand Up @@ -43,6 +43,9 @@ export class Anthology {
@Column({ nullable: true })
shopify_url: string;

@OneToMany(() => Story, (story) => story.anthology)
stories?: Story[];

// TODO once Library is implemented
// @Column()
// library_id:
Expand Down
13 changes: 13 additions & 0 deletions apps/backend/src/anthology/anthology.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { Anthology } from './anthology.entity';
import { Story } from '../story/story.entity';
import { AnthologyStatus, AnthologyPubLevel } from './types';

@Injectable()
export class AnthologyService {
constructor(
@InjectRepository(Anthology) private repo: Repository<Anthology>,
@InjectRepository(Story) private storyRepo: Repository<Story>,
) {}

async create(
Expand Down Expand Up @@ -120,4 +122,15 @@ export class AnthologyService {
anthology.status = status;
return this.repo.save(anthology);
}

async getStories(anthologyId: number): Promise<Story[]> {
const anthology = await this.repo.findOne({ where: { id: anthologyId } });
if (!anthology) {
throw new NotFoundException('Anthology not found');
}

return this.storyRepo.find({
where: { anthology: { id: anthologyId } },
});
}
}
18 changes: 18 additions & 0 deletions apps/backend/src/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { UsersService } from '../users/users.service';

describe('AuthController', () => {
let controller: AuthController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuthController],
providers: [
{
provide: AuthService,
useValue: {
login: jest.fn(),
register: jest.fn(),
},
},
{
provide: UsersService,
useValue: {
findOne: jest.fn(),
create: jest.fn(),
},
},
],
}).compile();

controller = module.get<AuthController>(AuthController);
Expand Down
5 changes: 5 additions & 0 deletions apps/backend/src/library/library.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Library } from './library.entity';
import { Anthology } from '../anthology/anthology.entity';
import { AnthologyService } from '../anthology/anthology.service';
import { CreateAnthologyDto } from '../anthology/dtos/create-anthology.dto';
import { Story } from '../story/story.entity';

@Injectable()
export class LibraryService {
Expand Down Expand Up @@ -90,6 +91,10 @@ export class LibraryService {
return library.anthologies;
}

async getAnthologyStories(anthologyId: number): Promise<Story[]> {
return this.anthologyService.getStories(anthologyId);
}

async createAnthology(
libraryId: number,
createAnthologyDto: CreateAnthologyDto,
Expand Down
8 changes: 2 additions & 6 deletions apps/backend/src/story/story.entity.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Entity, Column, IntegerType } from 'typeorm';
import { Entity, Column, IntegerType, ManyToOne, JoinColumn } from 'typeorm';
import { Anthology } from '../anthology/anthology.entity';

@Entity()
export class Story {
Expand All @@ -23,12 +24,7 @@ export class Story {
@Column()
theme?: string;

@Column()
anthology_id?: number;

/*
@ManyToOne(() => Anthology)
@JoinColumn({ name: 'anthology_id' })
anthology?: Anthology;
*/
}
3 changes: 2 additions & 1 deletion apps/backend/src/story/story.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export class StoryService {
anthology_id?: number,
) {
const storyId = (await this.repo.count()) + 1;

const story = this.repo.create({
id: storyId,
title,
Expand All @@ -26,7 +27,7 @@ export class StoryService {
description,
genre,
theme,
anthology_id,
anthology: anthology_id ? { id: anthology_id } : undefined, // ✅ use relation instead of anthology_id
});

return this.repo.save(story);
Expand Down