Skip to content

Commit 72fefa2

Browse files
committed
update challenge 4
1 parent 3173d40 commit 72fefa2

File tree

5 files changed

+199
-27
lines changed

5 files changed

+199
-27
lines changed

javascript-validation-anhduy/index.js

+21-14
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,32 @@
11
const express = require('express');
2-
const app = express();
32
const PORT = 3001;
4-
const { validateUser } = require('./validation');
3+
const { joiSchema } = require('./schema');
4+
const { validate, ValidationError } = require('express-validation')
5+
6+
const app = express();
57

68
app.use(express.json());
79

8-
app.post('/api/users/register', async (req, res, next) => {
9-
try {
10-
const result = await validateUser(req.body);
11-
if (result.error) {
12-
res.status(400).json({
13-
error: result.error.details
14-
})
10+
11+
app.post('/api/users/register', validate({ body: joiSchema }, {}, {}),
12+
async (req, res, next) => {
13+
try {
14+
res.status(200).json({ data: {} });
15+
} catch (err) {
16+
console.log(err);
17+
next(err);
1518
}
16-
res.status(200).json();
17-
} catch(err) {
18-
console.log(err);
19-
next(err);
19+
});
20+
21+
//error handle middleware
22+
app.use(function (err, req, res, next) {
23+
if (err instanceof ValidationError) {
24+
return res.status(err.statusCode).json({ err });
2025
}
21-
})
26+
return res.status(500).json({ err });
27+
});
2228

29+
//app running
2330
app.listen(PORT, () => {
2431
console.log(`App listening on port ${PORT}`);
2532
});

javascript-validation-anhduy/package-lock.json

+165
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

javascript-validation-anhduy/package.json

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
"license": "ISC",
1111
"dependencies": {
1212
"express": "^4.18.2",
13+
"express-validation": "^4.1.0",
1314
"joi": "^17.6.3"
1415
}
1516
}
+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const Joi = require('joi');
2+
3+
4+
const joiSchema = Joi.object({
5+
first_name: Joi.string().max(40),
6+
last_name: Joi.string().max(40),
7+
email: Joi.string().email(),
8+
password: Joi.string().min(8).pattern(new RegExp('^[a-zA-Z]+$')),
9+
password_confirmation: Joi.ref('password')
10+
});
11+
12+
module.exports = { joiSchema };

javascript-validation-anhduy/validation.js

-13
This file was deleted.

0 commit comments

Comments
 (0)