11import postgres from "postgres" ;
22
3- import { Category , Image , LocalImageInfo , TagEntry , TagMap } from "../types/drawref.js" ;
3+ import { Category , CategoryImagePage , Image , LocalImageInfo , TagEntry , TagMap } from "../types/drawref.js" ;
44import urlJoin from "url-join" ;
55import { allowLocalImages , myURL , uploadUrlPrefix } from "../config/env.js" ;
66
7+ const defaultImagesPerPage = 20 ;
8+
79function tagMapToDbTags ( tags : TagMap ) : string [ ] {
810 if ( tags === undefined ) {
911 return [ ] ;
@@ -389,16 +391,32 @@ class Database {
389391 }
390392 }
391393
392- async getCategoryImages ( category : string , page : number ) : Promise < Image [ ] > {
394+ async getCategoryImages ( category : string , page : number ) : Promise < CategoryImagePage > {
393395 var images : Image [ ] = [ ] ;
394396
395- const rows = await this . sql `
397+ // get all entries
398+ let rows = await this . sql `
399+ select count(*) as count
400+ from images
401+ inner join image_tags
402+ on images.id = image_tags.image_id
403+ where image_tags.category_id = ${ category }
404+ ` ;
405+
406+ const totalImages = rows [ 0 ] . count ;
407+ // const startAtImage = Math.max(page, 0) * defaultImagesPerPage;
408+ // const endAtImage = startAtImage + Math.min(defaultImagesPerPage, totalImages - startAtImage) - 1;
409+
410+ // get this page
411+ rows = await this . sql `
396412 select image_id, path, external_url, author, author_url, is_local, image_tags.tags
397413 from images
398414 inner join image_tags
399415 on images.id = image_tags.image_id
400416 where image_tags.category_id = ${ category }
401417 order by image_tags.created_at desc
418+ limit ${ defaultImagesPerPage }
419+ offset ${ defaultImagesPerPage * page }
402420 ` ;
403421 for ( const row of rows ) {
404422 var img : Image = {
@@ -413,7 +431,12 @@ class Database {
413431 images . push ( img ) ;
414432 }
415433
416- return images ;
434+ return {
435+ images,
436+ total_images : totalImages ,
437+ page,
438+ total_pages : Math . ceil ( totalImages / defaultImagesPerPage ) ,
439+ } ;
417440 }
418441
419442 async getSessionImages ( category : string , tags : TagMap ) : Promise < Image [ ] > {
0 commit comments