Skip to content

Instantly share code, notes, and snippets.

@saman-ghm
Created January 30, 2020 20:32
Show Gist options
  • Save saman-ghm/fc51e9cd33d0728b0585c04d671b48f1 to your computer and use it in GitHub Desktop.
Save saman-ghm/fc51e9cd33d0728b0585c04d671b48f1 to your computer and use it in GitHub Desktop.
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();
class ValidationResult {
data: any;
error: any;
}
async function validateAndConvert(classToConvert: any, body: string) {
const result = new ValidationResult();
result.data = plainToClass(classToConvert, body);
await validate(result.data, { 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);
}
result.error = errorTexts;
return result;
}
});
return result;
}
router.post("/user/submit", async (req: Request, res: Response) => {
const conversionResult = await validateAndConvert(UserDto, req.body);
if (conversionResult.error) {
res.status(400).send(conversionResult.error);
} else {
res.json(conversionResult.data);
}
});
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