Skip to content

Commit

Permalink
randome quote for a single day
Browse files Browse the repository at this point in the history
  • Loading branch information
brubluenel committed Sep 12, 2024
1 parent 4037650 commit 590be9d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/random-quote/random-quote.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ export class RandomQuoteController {
}

@Get()
async getDailyQuote(): Promise<Quote> {
// Use the service to get the daily quote
return this.randomQuoteService.findDailyQuote();
}

@Get('all-quotes')
findAll(): Promise<Quote[]> {
return this.randomQuoteService.findAll();
}
Expand Down
26 changes: 26 additions & 0 deletions src/random-quote/random-quote.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,32 @@ export class RandomQuoteService {
return this.quotesRepository.save(newQuote);
}

async findDailyQuote(): Promise<Quote> {
// Get the total number of quotes without fetching them all
const count = await this.quotesRepository.count();

if (count === 0) {
throw new Error('No quotes found');
}

// Calculate the day of the year (1-365/366)
const today = new Date();
const start = new Date(today.getFullYear(), 0, 0);
const diff = (today as any) - (start as any);
const oneDay = 1000 * 60 * 60 * 24;
const dayOfYear = Math.floor(diff / oneDay);

// Select the quote based on the day of the year, using an offset query
const quoteIndex = dayOfYear % count;
const quote = await this.quotesRepository
.createQueryBuilder("quote")
.offset(quoteIndex) // Skip to the correct quote
.limit(1) // Only fetch one quote
.getOne();

return quote;
}

findAll(): Promise<Quote[]> {
return this.quotesRepository.find();
}
Expand Down

0 comments on commit 590be9d

Please sign in to comment.