summary refs log tree commit diff
path: root/src/db
diff options
context:
space:
mode:
authorRory& <root@rory.gay>2025-06-01 04:40:09 +0200
committerRory& <root@rory.gay>2025-06-01 04:40:09 +0200
commita22c00fcefa10a99505c05393106fb3a655de243 (patch)
tree417757b1e5aa9f44702ed963569e0edf6209043d /src/db
parentAdd some tests (diff)
downloadnodejs-final-assignment-a22c00fcefa10a99505c05393106fb3a655de243.tar.xz
Add register with validation
Diffstat (limited to 'src/db')
-rw-r--r--src/db/dbAccess/user.js22
-rw-r--r--src/db/dbAccess/user.test.js2
2 files changed, 13 insertions, 11 deletions
diff --git a/src/db/dbAccess/user.js b/src/db/dbAccess/user.js

index 413b1cf..6301cb5 100644 --- a/src/db/dbAccess/user.js +++ b/src/db/dbAccess/user.js
@@ -1,23 +1,25 @@ import { hash, compare } from 'bcrypt'; import { DbUser } from '#db/schemas/index.js'; +import { RegisterDto } from '#dto/auth/index.js'; -export async function registerUser(username, password, email, type = 'user') { - if (!username || !password || !email) { - throw new Error( - 'Username, password, and email are required to register a user.' - ); - } +/** + * @param data {RegisterDto} + * @returns {Promise<(Error | HydratedDocument<InferSchemaType<module:mongoose.Schema>, ObtainSchemaGeneric<module:mongoose.Schema, "TVirtuals"> & ObtainSchemaGeneric<module:mongoose.Schema, "TInstanceMethods">, ObtainSchemaGeneric<module:mongoose.Schema, "TQueryHelpers">, ObtainSchemaGeneric<module:mongoose.Schema, "TVirtuals">>)[]>} + */ +export async function registerUser(data) { + if (!(data instanceof RegisterDto)) + throw new Error('Invalid data type. Expected RegisterDto.'); - const passwordHash = await hash(password, 10); + const passwordHash = await hash(data.password, 10); if (!passwordHash) { throw new Error('Failed to hash password.'); } return DbUser.create({ - username, + username: data.username, passwordHash, - email, - type + email: data.email, + type: data.type }); } diff --git a/src/db/dbAccess/user.test.js b/src/db/dbAccess/user.test.js
index e8e1af5..7b72d29 100644 --- a/src/db/dbAccess/user.test.js +++ b/src/db/dbAccess/user.test.js
@@ -26,7 +26,7 @@ await it('Can create user', async () => { }); await it('Can delete user', async () => { - const { username, password, email, user } = await createTestUser(); + const { password, user } = await createTestUser(); const deletePromise = deleteUser(user._id, password); await assert.doesNotReject(deletePromise);