Created
September 9, 2021 10:32
-
-
Save tsh-code/eb5c99b83abbe5cc0666f68f0ead5341 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 { 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