-
Notifications
You must be signed in to change notification settings - Fork 0
/
places.js
90 lines (72 loc) · 2.3 KB
/
places.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import Place from '../models/place.js';
const insertPlace = async (req, res) => {
const body = req.body;
const newPlace = await Place.create({
name: body.name,
province: body.province
});
console.log(newPlace);
res.json({ placeId: newPlace._id.toString() });
};
const getPlaceById = async (req, res) => {
const placeId = req.params.id;
// if (!placeId) {
// res.status(400);
// throw new Error('Place ID hasn\'t been sent');
// }
if (typeof placeId !== 'string') {
res.status(400);
throw new Error('Place ID is not string type');
}
if (placeId.length !== 24) {
res.status(400);
const lengthMessage = placeId.length < 24 ? 'short' : 'long';
throw new Error(`Place ID '${placeId}' is too ${lengthMessage} (24 characters)`);
}
const place = await Place.findById(placeId);
if (!place) {
res.status(404);
throw new Error(`Place '${placeId}' not found`);
}
res.json(place);
};
const getAllPlaces = async (req, res) => {
const places = await Place.find({}).exec();
if (places.length === 0) {
res.status(404);
throw new Error(`Places ${stopId} not found`);
}
res.json(places);
};
const getPlaceByName = async (req, res) => {
const placeName = req.params.name;
if (typeof placeName !== 'string') {
res.status(400);
throw new Error('Place name is not string type');
}
const place = await Place.findOne({
name: { $regex: new RegExp(`.*${placeName}.*`, 'i') }
});
if (!place) {
res.status(404);
throw new Error(`Place '${placeName}' not found`);
}
res.json(place);
};
const getPlacesByProvince = async (req, res) => {
const provinceName = req.params.name;
if (typeof provinceName !== 'string') {
res.status(400);
throw new Error(`Place province is not string type`);
}
const places = await Place.find({
province: { $regex: new RegExp(`.*${provinceName}.*`, 'i') }
})
.exec();
if (places.length === 0) {
res.status(404);
throw new Error(`Places with province '${provinceName}' not found`);
}
res.json(places);
};
export { insertPlace, getAllPlaces, getPlaceById, getPlaceByName, getPlacesByProvince };