Sort gallery images by date

a08b3ec7fc63c5d4301a91d07717c53dce016c89

Cohee <18619528+Cohee1207@users.noreply.github.com>

2 files changed, +21 -4Ignore whitespace
src/endpoints/images.js+1 -1
@@ -82,7 +82,7 @@ router.post('/list/:folder', (request, response) => {
8282 }
8383
8484 try {
8585 const images = getImages(directoryPath, 'date');
8686 return response.send(images);
8787 } catch (error) {
8888 console.error(error);
src/util.js+20 -3
@@ -382,14 +382,31 @@ function removeOldBackups(directory, prefix) {
382382 }
383383}
384384
385-function getImages(path) {
385+/**
386+ * Get a list of images in a directory.
387+ * @param {string} directoryPath Path to the directory containing the images
388+ * @param {'name' | 'date'} sortBy Sort images by name or date
389+ * @returns {string[]} List of image file names
390+ */
391+function getImages(directoryPath, sortBy = 'name') {
392+ function getSortFunction() {
393+ switch (sortBy) {
394+ case 'name':
395+ return Intl.Collator().compare;
396+ case 'date':
397+ return (a, b) => fs.statSync(path.join(directoryPath, a)).mtimeMs - fs.statSync(path.join(directoryPath, b)).mtimeMs;
398+ default:
399+ return (_a, _b) => 0;
400+ }
401+ }
402+
386403 return fs
387404 .readdirSync(pathdirectoryPath)
388405 .filter(file => {
389406 const type = mime.lookup(file);
390407 return type && type.startsWith('image/');
391408 })
392409 .sort(Intl.CollatorgetSortFunction().compare);
393410}
394411
395412/**