Created
January 30, 2020 19:55
-
-
Save saman-ghm/c7896e64d6d7f6df17a05b6e17722039 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Router, Response, Request } from "express"; | |
import express from "express"; | |
import bodyParser from "body-parser"; | |
import { validate, Matches, IsDefined } from "class-validator"; | |
import { plainToClass, Expose } from "class-transformer"; | |
class UserDto { | |
@IsDefined() | |
@Expose() | |
username: String; | |
@IsDefined() | |
@Expose() | |
@Matches(RegExp(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/)) | |
password: String; | |
@IsDefined() | |
@Expose() | |
@Matches(RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) | |
email: String; | |
} | |
const app = express(); | |
app.use(bodyParser.json()); | |
app.use(bodyParser.urlencoded({ extended: true })); | |
const router = Router(); | |
router.post("/user/submit", async (req: Request, res: Response) => { | |
const user = plainToClass(UserDto, req.body); | |
validate(user, { skipMissingProperties: true }).then(errors => { | |
// errors is an array of validation errors | |
if (errors.length > 0) { | |
let errorTexts = Array(); | |
for (const errorItem of errors) { | |
errorTexts = errorTexts.concat(errorItem.constraints); | |
} | |
res.status(400).send(errorTexts); | |
return; | |
} else { | |
// pass 'user' object to repository/service | |
res.json(user); | |
} | |
}); | |
}); | |
app.use(router); | |
app.listen(3000, () => { | |
console.log('Server is running in http://localhost:3000'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment