일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- recyclerview
- map
- elementAt
- react native
- Kotlin
- Generic
- class component
- Swift
- AWS
- collection
- animation
- vuex
- MINUS
- union
- Service
- LiveData
- 생명주기
- CLASS
- mongoose
- Interface
- ConstraintLayout
- docker
- function
- Filter
- enum
- lifecycle
- Foreign Key
- docker-compose
- ReactNative
- list
- Today
- Total
개발 일기
express-validator ? 본문
express-validator는 validator에서 파생된 오픈 소스 모듈입니다.
따라서 요청 객체에 (req) 대해서 유효값 검사를 진행을 할수가 있습니다.
기존에서는 Joi를 통한 Validator를 진행을 하고 있었는데
Express-validator가 더 편한 방법을 제공해주는 것 같아 변경하게 되었습니다.
설치 :)
npm install --save express-validator
기본적으로는 아래와 같이 사용이 가능합니다.
// ...rest of the initial code omitted for simplicity.
const { check, validationResult } = require('express-validator');
app.post('/user', [
// username must be an email
check('username').isEmail(),
// password must be at least 5 chars long
check('password').isLength({ min: 5 })
], (req, res) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
User.create({
username: req.body.username,
password: req.body.password
}).then(user => res.json(user));
});
위에서는 username 이 email 형식 , password 길이가 5개를 넘지 못한다면 아래와 같은 에러를 주게 됩니다.
{
"errors": [{
"location": "body",
"msg": "Invalid value",
"param": "username"
}]
}
Chain :)
const express = require('express');
const { body } = require('express-validator');
const app = express();
app.use(express.json());
app.post('/comment', [
body('email')
.isEmail()
.normalizeEmail(),
body('text')
.not().isEmpty()
.trim()
.escape(),
body('notifyOnReply').toBoolean()
], (req, res) => {
// Handle the request somehow
});
위에서와 같이 validator에서 제공하는 함수를 체인형식으로 통해서도 구현하실수 있습니다.
Custom Validator :)
Custom Validator는 .custom() 을 통해서 구현하실수 있습니다.
Custom Validators 는 Promise를 통하여 return 또는 throw 을 통하여 예외 처리를 진행 할수 있습니다.
const { body } = require('express-validator');
app.post('/user',
body('email').custom(value => {
return User.findUserByEmail(value).then(user => {
if (user) {
return Promise.reject('E-mail already in use');
}
});
}),
body('passwordConfirmation').custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation does not match password');
}
// Indicates the success of this synchronous custom validator
return true;
}),
(req, res) => {
// Handle the request
});
Error Message :)
express-validator는 기본적으로 에러메시지는 Invalid value을 제공합니다.
이것은 대부분은 조건에서는 충족을 하지만
필요한 경우 추가적으로 에러메시지를 작성하실수 있습니다.
각각의 Validator에 에러메시지를 작성하고 싶으면 .withMessage() 을 통하여 작성이 가능합니다.
const { check } = require('express-validator');
app.post('/user', [
// ...some other validations...
check('password')
.isLength({ min: 5 }).withMessage('must be at least 5 chars long')
.matches(/\d/).withMessage('must contain a number')
], (req, res) => {
// Handle the request somehow
});
만약에 동적으로 에러메시지를 변환 하고 싶으면
아래와 같이 변환 시킬수 있습니다.
// check(field, withMessage) and .withMessage() work the same
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
check('somethingElse', (value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
return req.translate('validation.multiple_failures');
});
Wildcards :)
가끔식 같은 규칙을 특정한 키의 모든 아이템에 적용을 시키고 싶은 경우가 있습니다.
예를 들어 01012345678.number로 앞에 있는부분을 체크하고 싶을 경우 아래와 같이 체크하여 전체 적용을 시킬수가 있습니다.
const express = require('express');
const { check, sanitize } = require('express-validator');
const app = express();
app.use(express.json());
app.post('/addresses', [
sanitize('data*.number').toInt()
], (req, res) => {
// Handle the request
});
Schema Validation :)
이부분에 관련해서는 Joi 가 더 편한 부분이 있는거 같다.
관련해서는 링크로 남겨두겠습니다.
Whole Body Validation :)
가끔식 POST 요청에 body에 관련된 모든 내용을 유효성 검사를 실행을 하고 싶을떄 아래와 같은 방법으로 실행할수 있습니다.
const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');
const app = express();
// Will handle text/plain requests
app.use(bodyParser.text());
app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});
간단하게 사용하는 방법 :)
아래와 같이 공통된 작업을 간단하게 넘기는 방법을 사용하실수도 있습니다.
// can be reused by many routes
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));
const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}
res.status(422).json({ errors: errors.array() });
};
};
app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});
'서버 > Node.js' 카테고리의 다른 글
body-parser (0) | 2020.03.27 |
---|---|
Sharp ( 이미지 resize ) (0) | 2020.03.26 |
Gulp ? (0) | 2020.03.18 |
Npm ? (0) | 2020.03.15 |
Express 란? (0) | 2020.03.07 |