Skip to content

Commit 2a5f5e4

Browse files
committed
added pagination and sorting
1 parent 4535f36 commit 2a5f5e4

File tree

1 file changed

+45
-16
lines changed

1 file changed

+45
-16
lines changed

server/endpoints/videos.ts

Lines changed: 45 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,59 @@
1-
import express from 'express';
1+
import 'dotenv/config';
2+
import express, {Request, Response} from 'express';
23
import fs from 'fs';
3-
import { getDb } from '../db/mongo';
4+
import {ObjectId} from 'mongodb';
5+
import {getDb} from '../db/mongo.js';
46

7+
/* eslint new-cap: ["error", { "capIsNewExceptions": ["Router"] }] */
58
const videos = express.Router();
69

7-
videos.get('/', function (_req, res) {
10+
videos.get('/', function(req: Request, res: Response) {
11+
let page = 1;
12+
const rpp = 12;
813
const db = getDb();
914

15+
if (req.query.page !== undefined) {
16+
page = parseInt(req.query.page as string);
17+
}
18+
19+
const skip = (page - 1) * rpp;
20+
1021
db.collection('videos')
11-
.find({})
12-
.toArray(function (err: any, result: any) {
13-
if (err) {
14-
res.status(400).send('Error fetching listings!');
15-
} else {
16-
res.json({items: result});
17-
}
18-
});
22+
.aggregate([
23+
{
24+
$facet: {
25+
items: [
26+
{$match: {status: 2}},
27+
{$sort: {ts: -1}},
28+
{$skip: skip},
29+
{$limit: rpp},
30+
],
31+
total: [{$count: 'count'}],
32+
},
33+
},
34+
])
35+
.toArray(function(err: any, result: any) {
36+
if (err) {
37+
res.status(400).send('Error fetching listings!');
38+
} else {
39+
res.json(result);
40+
}
41+
});
1942
});
2043

21-
videos.get('/thumb/:videoId', function (req, res) {
44+
videos.get('/thumb/:videoId', function(req: Request, res: Response) {
2245
const videoId = req.params.videoId;
23-
let filename = videoId;
46+
const db = getDb();
2447

25-
var img = fs.readFileSync('store/videos/thumbs/' + filename);
26-
res.writeHead(200, { 'Content-Type': 'image/png' });
27-
res.end(img, 'binary');
48+
db.collection('videos')
49+
.findOne({_id: new ObjectId(videoId)})
50+
.then((result: any) => {
51+
const img = fs.readFileSync(
52+
`${process.env.STORAGE}/videos${result.path}/thumbs/${videoId}`,
53+
);
54+
res.writeHead(200, {'Content-Type': 'image/png'});
55+
res.end(img, 'binary');
56+
});
2857
});
2958

3059
export default videos;

0 commit comments

Comments
 (0)