self.js 1.02 KB
Newer Older
abergavenny's avatar
abergavenny committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { Building, User } from '../db/index.js'
import { getUserFromRequest, success, warning } from '../helpers/index.js'

import { ResponseCode } from '../ENUMS.js'

export const getSelf = async (req, res) => {
  const { accessor, role } = getUserFromRequest(req)

  const user = await User.findById(accessor).select('_id role linkedTo sharingAllowed')

  if (user) {
    let apartmentCount, buildingCount, buildingList

    if (role === 'administrator') {
      const buildings = await Building.find({ owner: user._id })

      apartmentCount = buildings.apartments?.length || 0
      buildingCount = buildings.length
      buildingList = buildings.map(element => element._id)
    }

    return success(res, {
      code: ResponseCode.Success,
      data: {
        id: user._id,
        apartments: apartmentCount,
        buildings: buildingCount,
        buildingList,
        sharingAllowed: user.sharingAllowed,
        linkedTo: user.linkedTo,
        role: user.role
      }
    })
  }

  warning(res, { code: ResponseCode.NotFound })
}