test to save only if feed item does not exist

This commit is contained in:
albert
2025-07-29 01:19:44 +02:00
parent f3fffa6f88
commit 5ed38dcc98
2 changed files with 29 additions and 0 deletions

View File

@ -94,5 +94,26 @@ describe('ScrapingService', () => {
expect(mockFeedRepository.findByUrl).toHaveBeenCalledWith(testUrl);
expect(exists).toBe(true);
});
test('should save feed item only if it does not exist', async () => {
const feedData = {
title: 'New News',
description: 'New description',
url: 'https://example.com/new-news',
source: 'El País' as any,
publishedAt: new Date(),
isManual: false
};
const savedFeed = { _id: '2', ...feedData };
mockFeedRepository.findByUrl.mockResolvedValue(null);
mockFeedRepository.create.mockResolvedValue(savedFeed);
const result = await scrapingService.saveIfNotExists(feedData);
expect(mockFeedRepository.findByUrl).toHaveBeenCalledWith(feedData.url);
expect(mockFeedRepository.create).toHaveBeenCalledWith(feedData);
expect(result).toEqual(savedFeed);
});
});
});

View File

@ -24,4 +24,12 @@ export class ScrapingService {
const existingFeed = await this.feedRepository.findByUrl(url);
return existingFeed !== null;
}
async saveIfNotExists(feedData: Omit<IFeed, '_id' | 'createdAt' | 'updatedAt'>): Promise<IFeed | null> {
const exists = await this.feedExists(feedData.url);
if (exists) {
return null;
}
return await this.saveFeedItem(feedData);
}
}