Skip to content

Commit

Permalink
imnplement ValidationError
Browse files Browse the repository at this point in the history
  • Loading branch information
mpfeil committed Jan 13, 2025
1 parent 5d6493f commit b4e60b7
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/models/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"mongoose-timestamp": "^0.6",
"pg": "^8.13.0",
"pino": "^8.8.0",
"tiny-invariant": "^1.3.3",
"uuid": "^8.3.2"
},
"scripts": {
Expand Down
23 changes: 23 additions & 0 deletions packages/models/src/user/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const { v4: uuidv4 } = require('uuid');
const invariant = require('tiny-invariant');

const { userTable, passwordTable } = require('../../schema/schema');
const { db } = require('../drizzle');
Expand All @@ -9,6 +10,18 @@ const { eq } = require('drizzle-orm');
const ModelError = require('../modelError');
const { checkPassword, validatePassword, passwordHasher } = require('../password/utils');

const validateField = function validateField (field, expr, msg) {
try {
invariant(expr, msg);
} catch (error) {
const err = new Error();
err.name = 'ValidationError';
err.errors = [];
err.errors[field] = { message: msg };
throw err;
}
}

const findUserByNameOrEmail = async function findUserByNameOrEmail (
emailOrName
) {
Expand Down Expand Up @@ -37,7 +50,16 @@ const findUserByEmailAndRole = async function findUserByEmailAndRole ({
};

const createUser = async function createUser (name, email, password, language) {

try {
validateField('name', name.length > 0, 'Name is required');
validateField('password', validatePassword(password), 'Password must be at least 8 characters');
} catch (error) {
throw error;
}

try {
// TODO: Wrap this in a transaction
const hashedPassword = await passwordHasher(password);
const user = await db
.insert(userTable)
Expand All @@ -55,6 +77,7 @@ const createUser = async function createUser (name, email, password, language) {
return user[0];
} catch (error) {
console.log(error);
throw error;
}
};

Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4237,6 +4237,11 @@ thread-stream@^3.0.0:
dependencies:
real-require "^0.2.0"

tiny-invariant@^1.3.3:
version "1.3.3"
resolved "https://registry.yarnpkg.com/tiny-invariant/-/tiny-invariant-1.3.3.tgz#46680b7a873a0d5d10005995eb90a70d74d60127"
integrity sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==

to-regex-range@^5.0.1:
version "5.0.1"
resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4"
Expand Down

0 comments on commit b4e60b7

Please sign in to comment.