Skip to content

Instantly share code, notes, and snippets.

@PaulBGD
Last active January 2, 2016 08:28
Show Gist options
  • Save PaulBGD/d7584482a61307433f4b to your computer and use it in GitHub Desktop.
Save PaulBGD/d7584482a61307433f4b to your computer and use it in GitHub Desktop.
Easy Validation
/// <reference path="../../typings/tsd.d.ts" />
import {Router, Request, Response} from 'express';
import * as ArtisanValidator from 'artisan-validator';
import {DatabaseClient, DatabaseError} from '../database';
let ClientAPI: Router = Router();
let validator: ArtisanValidator.Validator = ArtisanValidator();
validator.validators.add(function gender(key: string, gender: string) {
return gender === 'MALE' || gender === 'FEMALE';
});
validator.language.extend('gender', 'Invalid gender %s.');
validator.validators.add(function base64(key: string, image: string) {
return /^(?:[A-Z0-9+\/]{4})*(?:[A-Z0-9+\/]{2}==|[A-Z0-9+\/]{3}=|[A-Z0-9+\/]{4})$/i.test(image);
});
validator.language.extend('base64', 'Invalid image.');
interface RegisterRules {
name: string[];
email: string[];
password: string[];
gender: string[];
avatar: string[];
}
let registerRules: RegisterRules = {
name: ['required', 'between 3, 60'],
email: ['required', 'between 4, 50', 'email'],
password: ['required', 'between 6, 50'],
gender: ['required', 'gender'],
avatar: ['required', 'base64']
};
ClientAPI.post('/register', (req: Request, res: Response) => {
validator.try(req.body, registerRules).then((result: ArtisanValidator.ValidatorResult<RegisterRules>) => {
if (result.failed) {
return res.json({error: true, errors: result.errors})
}
DatabaseClient.createAccount(req.body).then(() => {
res.json({error: false});
}).catch(DatabaseError, (error: DatabaseError) => {
res.json({error: true, message: error.message});
if (error.original) {
throw error.original;
}
});
}).catch(error => {
if (!res.headersSent) {
res.json({error: true, message: 'A server error occurred.'});
}
throw error;
});
});
interface LogInRules {
email: string[];
password: string[];
}
let loginRules: LogInRules = {
email: ['required', 'between 4, 50', 'email'],
password: ['required', 'between 6, 50']
};
ClientAPI.post('/login', (req: Request, res: Response) => {
validator.try(req.body, loginRules).then((result: ArtisanValidator.ValidatorResult<LogInRules>) => {
if (result.failed) {
return res.json({error: true, errors: result.errors});
}
DatabaseClient.logIn(req.body.email, req.body.password).then(() => {
res.json({error: false});
}).catch(DatabaseError, (error: DatabaseError) => {
res.json({error: true, message: error.message});
if (error.original) {
throw error.original;
}
});
}).catch(error => {
if (!res.headersSent) {
res.json({error: true, message: 'A server error occurred.'});
}
throw error;
});
});
export default ClientAPI;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment