Skip to content

Instantly share code, notes, and snippets.

@tsh-code
Created September 9, 2021 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsh-code/eb5c99b83abbe5cc0666f68f0ead5341 to your computer and use it in GitHub Desktop.
Save tsh-code/eb5c99b83abbe5cc0666f68f0ead5341 to your computer and use it in GitHub Desktop.
import { RequestHandler } from "express";
import { Connection } from "./connection";
import Joi from "joi";
export interface User {
email: string;
password: string;
}
export class UserModel implements User {
constructor(public email: string, public password: string) {}
// Return fields that can be publicly accessible
get publicData() {
return {
email: this.email,
};
}
}
const userSchema = Joi.object<User>({
// Ensure that email is valid and that it is not too long
email: Joi.string().email().required().max(100),
// Ensure that password is secure enough
password: Joi.string().min(5).max(50),
});
// Inject “Connection” here for easier testing
export const makeCreateUser =
(connection: Connection): RequestHandler =>
async (req, res) => {
// Note - this should be done via middleware, but for purposes of this
// article it’s done here instead
const validationResult = userSchema.validate(req.body);
if (validationResult.error) {
throw validationResult.error;
}
// At this point we know that all the values are valid!
const { email, password } = validationResult.value;
const user = new UserModel(email, password);
await connection.save(user);
res.json({
result: user.publicData,
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment