pengunjung.controller.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const pengunjungModel = require('../model/pengunjung.model')
  2. const handleError = require('../utils/handleError')
  3. const response = require('../utils/responseHandler')
  4. const { validate } = require('../utils/validation')
  5. exports.create = handleError(async (req, res) => {
  6. const { os, ipv4, location } = req.body
  7. const isValid = validate(res, req.body, {
  8. os: 'string',
  9. ipv4: 'string',
  10. location: {
  11. $$type: 'object',
  12. country: 'string',
  13. region: 'string',
  14. city: 'string',
  15. lat: 'number',
  16. lon: 'number',
  17. timezone: 'string',
  18. },
  19. })
  20. if (!isValid) return
  21. await pengunjungModel.create({ os, ipv4, location })
  22. return response.success(res, {
  23. message: 'data pengunjung berhasil dibuat',
  24. })
  25. })
  26. exports.getPengunjung = handleError(async (req, res) => {
  27. const { tahun } = req.query
  28. let date = {}
  29. if (tahun) {
  30. date = {
  31. $expr: {
  32. $eq: [
  33. { $year: '$createdAt' },
  34. parseInt(tahun) || new Date().getFullYear(),
  35. ],
  36. },
  37. }
  38. }
  39. const pengunjung = await pengunjungModel.aggregate([
  40. { $match: date },
  41. {
  42. $group: {
  43. _id: {
  44. bulan: {
  45. $month: '$createdAt',
  46. },
  47. tahun: {
  48. $year: '$createdAt',
  49. },
  50. },
  51. jumlah_pengunjung: {
  52. $sum: 1,
  53. },
  54. },
  55. },
  56. ])
  57. return response.success(res, {
  58. message: 'data pengunjung',
  59. data: pengunjung,
  60. })
  61. })