|
1 | 1 | const TestimonialDao = require('../dao/testimonials'); |
2 | 2 | const { Testimonial } = require('../models'); |
| 3 | +const Pagination = require('../helpers/pagination'); |
3 | 4 | class TestimonialController { |
4 | 5 | static async updateTestimonials(req, res) { |
5 | 6 | const { id } = req.params; |
@@ -42,23 +43,65 @@ class TestimonialController { |
42 | 43 | } |
43 | 44 | } |
44 | 45 | static async getTestimonials(req, res) { |
| 46 | + if (!req.query.page) { |
| 47 | + try { |
| 48 | + const testimonials = await TestimonialDao.getTestimonials([ |
| 49 | + 'name', |
| 50 | + 'image', |
| 51 | + 'content', |
| 52 | + ]); |
| 53 | + |
| 54 | + if (!testimonials) { |
| 55 | + return res.status(404).json({ |
| 56 | + msg: 'There is no testimonials', |
| 57 | + }); |
| 58 | + } |
| 59 | + |
| 60 | + return res.json({ |
| 61 | + testimonials, |
| 62 | + }); |
| 63 | + } catch (error) { |
| 64 | + return res.status(500).json({ |
| 65 | + msg: 'Error while searching testimonials ', |
| 66 | + }); |
| 67 | + } |
| 68 | + } |
| 69 | + const pagination = new Pagination(req, res); |
| 70 | + const { page, size } = pagination.getPaginationParams(req, res); |
| 71 | + |
45 | 72 | try { |
46 | | - const testimonials = await Testimonial.findAll({ |
| 73 | + const testimonials = await Testimonial.findAndCountAll({ |
47 | 74 | attributes: ['name', 'image', 'content'], |
| 75 | + limit: size, |
| 76 | + offset: page * size, |
48 | 77 | }); |
49 | 78 |
|
50 | | - if (!testimonials) { |
| 79 | + let totalPages = pagination.getNumberOfTotalPages( |
| 80 | + testimonials.count, |
| 81 | + size |
| 82 | + ); |
| 83 | + |
| 84 | + if (testimonials.count < 1) { |
51 | 85 | return res.status(404).json({ |
52 | 86 | msg: 'There is no testimonials', |
53 | 87 | }); |
54 | 88 | } |
55 | 89 |
|
| 90 | + const { nextPage, previousPage } = pagination.getNextAndPreviousPage( |
| 91 | + page, |
| 92 | + size, |
| 93 | + totalPages |
| 94 | + ); |
| 95 | + |
56 | 96 | return res.status(200).json({ |
57 | | - testimonials, |
| 97 | + content: testimonials.rows, |
| 98 | + totalPages, |
| 99 | + nextPage, |
| 100 | + previousPage, |
58 | 101 | }); |
59 | 102 | } catch (error) { |
60 | 103 | return res.status(500).json({ |
61 | | - msg: 'error while searching in db', |
| 104 | + msg: 'Error while searching testimonials in db', |
62 | 105 | }); |
63 | 106 | } |
64 | 107 | } |
|
0 commit comments