All files / src/repository userRepository.js

100% Statements 26/26
100% Branches 10/10
100% Functions 10/10
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 525x     15x       3x 3x 3x       12x   11x 1x   25x 10x 10x       2x 3x 3x   2x       2x 3x 1x 1x     2x       2x 4x 1x           5x  
const uuid = require("uuid")
class UserRepository {
  constructor(data) {
    this.data = data;
  }
 
  save(userData) {
    this.data.push({id: uuid.v4(), ...userData})
    const { password, ...user } = userData
    return user;
  }
 
  async find(value, field) {
    if(this.data.length === 0 ) return {}
 
    if (!this.data[0][field]) {
      throw new Error(`Field ${field} is not found in users`);
    }
    const user = this.data.find((user) => user[field] === value);
    delete user?.password;
    return user || {};
  }
 
  async findMany() {
    const data = await this.data.map(user => {
      const {password, ...userData } = user;
      return userData
    })
    return data;
  }
 
  async update(id, newData) {
    await this.data.find((user, idx) => {
      if (user.id === id) {
        this.data[idx] = { id, ...newData }
        return this.data[idx]
      }
    });
    return { id, ...newData }
  }
 
  delete(id) {
    this.data.find((user, idx) => {
      if (user.id === id) {
        this.data.splice(idx, 1)
      }
    });
  }
}
 
module.exports = UserRepository;