-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
170 lines (157 loc) · 5.64 KB
/
index.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
const express = require('express');
const lowdDB = require('lowdb');
const FyleSync = require('lowdb/adapters/FileSync');
const joi = require('joi');
const { nanoid } = require('nanoid');
const morgan = require('morgan');
// Server Setup
const PORT = 4000;
// Database Setup
const adapter = new FyleSync('db.json');
const db = lowdDB(adapter);
db.defaults({ users: [], hotels: [] }).write();
// Express Setup
const app = express();
// Global Middlewares
app.use(express.json());
app.use(morgan('dev'));
// Users
// fetch all users
app.get('/api/users', (req, res) => {
const users = db.get('users').value(); // query
res.status(200).json({ success: true, data: users });
});
// get an user by id
app.get('/api/users/:id', (req, res) => {
const { id } = req.params
const exists = db.get('users').find({ _id: id }).value(); // query
if (!exists) {
res.status(404).json({ success: false, message: 'User not found' });
} else {
res.status(200).json({ success: true, data: exists });
}
});
// create new user
app.post('/api/users', (req, res) => {
const body = req.body;
// data validation
const userSchema = joi.object({
name: joi.string().min(3).max(24).required(),
lastname: joi.string().min(3).max(24).required(),
email: joi.string().email().required(),
username: joi.string().min(3).max(20).alphanum().required(),
type: joi.string().valid('client', 'owner').required(),
phone: joi.string().length(10).pattern(/^[0-9]+$/)
});
const result = userSchema.validate(body);
const { value, error } = result;
const valid = error == null;
if (!valid) {
res.status(400).json({ success: false, message: 'Validation error', data: value, error: error });
} else {
// query if there is already an user with same email or username
const exists = db.get('users').find(user => user.email === body.email || user.username === body.username).value();
if (!exists) {
// data management for user creation
const user = {
_id: nanoid(),
...body,
createdAt: Date.now(),
};
// db management
db.get('users').push(user).write(); // mutation
res.status(201).json({ success: true, message: 'User has been created', data: user });
} else {
res.status(409).json({ success: false, message: 'Email or Username is already used' });
}
}
});
// update an existing user by id
app.patch('/api/users/:id', (req, res) => {
const id = req.params.id;
const body = req.body;
// validate data
const userSchema = joi.object({
name: joi.string().min(3).max(24),
lastname: joi.string().min(3).max(24),
email: joi.string().email()
});
const result = userSchema.validate(body);
const { value, error } = result;
const valid = error == null;
if (!valid) {
res.status(400).json({ success: false, message: 'Validation error', data: value, error: error });
} else {
const exists = db.get('users').find({ _id: id }).value(); // query
if (!exists) {
res.status(404).json({ success: false, message: 'User not found' });
} else {
const name = body.name ? body.name : exists.name;
const lastname = body.lastname ? body.lastname : exists.lastname;
const email = body.email ? body.email : exists.email;
const update = { name: name, lastname: lastname, email: email, updatedAt: Date.now() };
// db management
const user = db.get('users').find({ _id: id }).assign(update).write();
res.status(200).json({ success: true, message: 'User has been updated', data: user });
}
}
});
// delete an existing user by id
app.delete('/api/users/:id', (req, res) => {
const { id } = req.params
const exists = db.get('users').find({ _id: id }).value(); // query
if (!exists) {
res.status(404).json({ success: false, message: 'User not found' });
} else {
db.get('users').remove({ _id: id }).write(); // mutation
res.status(200).json({ success: true, message: 'User has been deleted' });
}
});
// Hotels
// fetch all hotels
app.get('/api/hotels', (req, res) => {
const hotels = db.get('hotels').value(); // query
res.status(200).json({ success: true, data: hotels });
});
// create new hotel
app.post('/api/hotels', (req, res) => {
const body = req.body;
// data validation
const userSchema = joi.object({
name: joi.string().min(3).max(24).required(),
phone: joi.string().length(10).pattern(/^[0-9]+$/),
email: joi.string().email().required(),
address: joi.string().min(10).max(42).required(),
ownerId: joi.string().required()
});
const result = userSchema.validate(body);
const { value, error } = result;
const valid = error == null;
if (!valid) {
res.status(400).json({ success: false, message: 'Validation error', data: value, error: error });
} else {
// query if there is already an hotel with same name
const exists = db.get('hotels').find({ name: body.name }).value();
// query if customerId is valid
const validOwnerId = db.get('users').find({ _id: body.ownerId, type: 'owner' }).value();
if (!exists && validOwnerId) {
// data management for hotel creation
const hotel = {
_id: nanoid(),
...body,
createdAt: Date.now(),
};
// db management
db.get('hotels').push(hotel).write(); // mutation
res.status(201).json({ success: true, message: 'Hotel has been created', data: hotel });
} else {
res.status(409).json({ success: false, message: 'Hotel name is already taken or owner id is not valid' });
}
}
});
// Custom middleware - express error handler
const errorHandler = require('./middlewares/errorHandler');
app.use(errorHandler);
app.listen(PORT, () => {
console.log(`App listening on ${PORT}`);
});