BikeTrips.ts 2.25 KB
Newer Older
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import StatusCodes from 'http-status-codes'
import { Request, Response, Router } from 'express'
import { ApiError, notFoundError, paramMissingError } from '@shared/responseTypes'
import { IBikeTrip } from '@entities/BikeTrip'
import { bikeTripsCollectionName, dbClient, dbName } from '@server'

const router = Router()
const { NOT_FOUND, OK } = StatusCodes

interface QueryParams {
    from: string
    to: string
}

interface IBikeTripsInRangeResponse {
    bikeTrips: IBikeTrip[]
}

interface IBikeTripResponse {
    bikeTrip: IBikeTrip
}

/******************************************************************************
 *         Get Bike Trips in range - "GET /api/bike-trips/all-in-range"
 ******************************************************************************/

router.get('/all-in-range', async (req: Request, res: Response<IBikeTripsInRangeResponse | ApiError>) => {
    const from = Number(req.query.from)
    const to = Number(req.query.to)

    if (!from || !to) {
        return res.status(StatusCodes.BAD_REQUEST).json({error: paramMissingError})
    }

    const bikeTripsCursor = dbClient.db(dbName).collection(bikeTripsCollectionName).aggregate<IBikeTrip>([
        {$match: {startDate: {$gte: from, $lt: to}}}
    ])

    return res.status(OK).json({bikeTrips: await bikeTripsCursor.toArray()})
})



/******************************************************************************
 *         Get single Bike Trip by rentalId - "GET /api/bike-trips/:rentalId"
 ******************************************************************************/

router.get('/:rentalId', async (req: Request, res: Response<IBikeTripResponse | ApiError>) => {
    const { rentalId } = req.params

    if (!rentalId) {
        return res.status(StatusCodes.BAD_REQUEST).json({error: paramMissingError})
    }

    const bikeTrip = await dbClient.db(dbName).collection(bikeTripsCollectionName).findOne({_id: rentalId})

    if (!bikeTrip) {
        return res.status(NOT_FOUND).json({error: notFoundError})
    }

    return res.status(OK).json({bikeTrip: bikeTrip})
})



/******************************************************************************
 *                                 Export
 ******************************************************************************/

export default router