diff --git a/controllers/api/searchController.js b/controllers/api/searchController.js index 09a48d6..97c56cc 100644 --- a/controllers/api/searchController.js +++ b/controllers/api/searchController.js @@ -1,14 +1,26 @@ const Software = require('../../models/software'); const searchSoftware = async (req, res) => { - const { name } = req.query; - const response = await Software.find({ + const page = parseInt(req.query.page, 10) || 0; + const perPage = parseInt(req.query.per_page, 10) || 30; + const query = { name: { - $regex: name, + $regex: req.query.q, $options: 'i', }, + }; + + const queryResponse = await Software.find(query) + .sort({ name: 'asc' }) + .skip(page * perPage) + .limit(perPage); + + const totalQueryResultCount = await Software.find(query).countDocuments(); + + return res.status(200).json({ + totalQueryResultCount, + queryResponse, }); - return res.status(200).json(response); }; module.exports = { diff --git a/models/software.js b/models/software.js index c05c58d..7f99759 100644 --- a/models/software.js +++ b/models/software.js @@ -34,9 +34,10 @@ const softwareSchema = new mongoose.Schema( homePage: { type: String, validate: [ - (value) => isURL(value, { - protocols: ['http', 'https'], - }), + (value) => + isURL(value, { + protocols: ['http', 'https'], + }), 'A valid url is required', ], required: [true, 'Software homepage url is required'], @@ -64,8 +65,9 @@ const softwareSchema = new mongoose.Schema( developedBy: { type: [ { - type: mongoose.Schema.Types.ObjectId, - ref: 'User', + type: String, + trim: true, + lowercase: true, }, ], default: [], @@ -73,8 +75,9 @@ const softwareSchema = new mongoose.Schema( maintainedBy: { type: [ { - type: mongoose.Schema.Types.ObjectId, - ref: 'User', + type: String, + trim: true, + lowercase: true, }, ], default: [], @@ -87,9 +90,10 @@ const softwareSchema = new mongoose.Schema( updateUrl: { type: String, validate: [ - (value) => isURL(value, { - protocols: ['http', 'https'], - }) || value === '', + (value) => + isURL(value, { + protocols: ['http', 'https'], + }) || value === '', 'A valid update url is required', ], default: '', @@ -97,9 +101,10 @@ const softwareSchema = new mongoose.Schema( downloadUrl: { type: String, validate: [ - (value) => isURL(value, { - protocols: ['http', 'https', 'ftp'], - }) || value === '', + (value) => + isURL(value, { + protocols: ['http', 'https', 'ftp'], + }) || value === '', 'A valid download url is required', ], default: '', diff --git a/requests/api/softwares/search_software.rest b/requests/api/softwares/search_software.rest index 7b9ce33..67d34cc 100644 --- a/requests/api/softwares/search_software.rest +++ b/requests/api/softwares/search_software.rest @@ -1 +1 @@ -GET http://localhost:3001/api/search/software?name=sample \ No newline at end of file +GET http://localhost:3001/api/search/software?q=sample&per_page=1&page=0 \ No newline at end of file