opt-cc/server/middleware/limitoffset-middleware-mong...

69 lines
1.9 KiB
JavaScript
Raw Permalink Normal View History

2017-10-10 19:03:52 +02:00
/** This module defines a express.Router() instance
* - supporting offset=<number> and limit=<number>*
* - calls next with error if a impossible offset and/or limit value is given
*
* Note: it expects to be called BEFORE any data fetched from DB
* Note: it sets an object { limit: 0, skip: 0 } with the proper number values in req.locals.limitskip
* Note: it sets an Error-Object to next with error.status set to HTTP status code 400
*
* @author Johannes Konert
* @licence CC BY-SA 4.0
*
* @module restapi/limitoffset-middleware-mongo
* @type {Router}
*/
// remember: in modules you have 3 variables given by CommonJS
// 1.) require() function
// 2.) module.exports
// 3.) exports (which is module.exports)
2018-03-12 09:26:44 +01:00
'use strict';
2017-10-10 19:03:52 +02:00
const express = require('express');
const router = new express.Router();
2017-10-10 19:03:52 +02:00
const logger = require('debug')('middleware:offsetlimit');
// the exported router with handler
router.use((req, res, next) => {
let offset = undefined;
let limit = undefined;
const offsetString = req.query.offset;
const limitString = req.query.limit;
let err = null;
if (offsetString) {
if (!isNaN(offsetString)) {
offset = parseInt(offsetString);
if (offset < 0) {
2018-03-12 09:26:44 +01:00
err = new Error('offset is negative');
2017-10-10 19:03:52 +02:00
}
2018-03-12 09:26:44 +01:00
} else {
2017-10-10 19:03:52 +02:00
err = new Error('given offset is not a valid number ' + offsetString);
}
}
if (limitString) {
if (!isNaN(limitString)) {
limit = parseInt(limitString);
if (limit < 1) {
2018-03-12 09:26:44 +01:00
err = new Error('limit is zero or negative');
2017-10-10 19:03:52 +02:00
}
2018-03-12 09:26:44 +01:00
} else {
2017-10-10 19:03:52 +02:00
err = new Error('given limit is not a valid number ' + limitString);
}
}
if (err) {
logger('problem occurred with limit/offset values');
err.status = 400;
2018-03-12 09:26:44 +01:00
next(err);
2017-10-10 19:03:52 +02:00
} else {
res.locals.limitskip = {}; // mongoDB uses parameter object for skip/limit
if (limit) res.locals.limitskip.limit = limit;
if (offset) res.locals.limitskip.skip = offset;
2018-03-12 09:26:44 +01:00
next();
2017-10-10 19:03:52 +02:00
}
});
module.exports = router;