Skip to content

Commit

Permalink
Improve random image lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
Turbotailz committed May 29, 2021
1 parent e93543e commit 8d05ebf
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions server/actions/get-image.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
const db = require('../../database');

let imageIds = [];

async function fetchImageIds() {
try {
const images = await db('images').select('id');
imageIds = images.map(({ id }) => id);
console.log(imageIds);
} catch (error) {
console.error(error);
}
}

(async function initImageArray() {
await fetchImageIds();
setInterval(fetchImageIds, 300000);
})();

async function getImage(id) {
return !isNaN(parseInt(id)) ? db('images').where({ id }).first() : null;
}
Expand All @@ -9,8 +26,8 @@ async function getImages(currentPage, sort) {
}

async function getRandomImage() {
const { rows } = await db.raw('SELECT * FROM images TABLESAMPLE SYSTEM_ROWS(1)');
return rows[0];
const randomId = imageIds[Math.floor(Math.random() * imageIds.length)];
return getImage(randomId);
}

async function getLatestImage() {
Expand Down

0 comments on commit 8d05ebf

Please sign in to comment.