Step 15: Update UserDao

We should update UserDao to account for the newly added role attribute.

We can start by adding a validator for role:

const validRole = z.enum(Object.values(UserRole));

Next, update the create method.

  • Pass role as a parameter
- async create({ name, email, password }) {
+ async create({ name, email, password, role }) {
  • Validate the role
if (role !== undefined) {
  debug("Validating the role..");
  result = validRole.safeParse(role);
  if (!result.success) {
    throw new ApiError(
      400,
      `Role should be. one of ${Object.keys(UserRole)}`
    );
  }
}
  • Pass role to User.create
- const user = await User.create({ name, email, password });
+ const user = await User.create({ name, email, password, role });

Next change the update method!

  • Pass role as a parameter
- async update({ id, name, email, password }) {
+ async update({ id, name, email, password, role }) {
  • Validate the role
if (role !== undefined) {
  debug("Validating the role..");
  result = validRole.safeParse(role);
  if (!result.success) {
    throw new ApiError(
      400,
      `Role should be. one of ${Object.keys(UserRole)}`
    );
  }
}
  • Pass role to User.findByIdAndUpdate
  const user = await User.findByIdAndUpdate(
    id,
-   { name, email, password },
+   { name, email, password, role },
    { new: true, runValidators: true }
  );

Finally, update the readAll method:

async readAll({ name, email, role }) {
  const filter = {};
  if (name) {
    filter.name = name;
  }

  if (email) {
    filter.email = email;
  }

  if (role) {
    filter.role = role;
  }

  debug("Reading all user documents..");
  const users = await User.find(filter);
  return users;
}

Refer to the commit history to see the changes made at this step.