/
InMemoryStudentRepository.js
95 lines (77 loc) · 2.32 KB
/
InMemoryStudentRepository.js
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* eslint-disable no-param-reassign */
/* eslint-disable arrow-body-style */
const StudentRepository = require('../../../application/contracts/StudentRepository');
module.exports = class InMemoryStudentRepository extends StudentRepository {
constructor() {
super();
this.students = [];
this.currentId = 1;
}
async add(studentInstance) {
try {
this.currentId = this.currentId + 1;
studentInstance.id = this.currentId;
this.students.push(studentInstance);
} catch (error) {
throw new Error('Error Occurred');
}
return studentInstance;
}
async update(studentInstance) {
let student;
try {
student = this.students.find(x => x.id === studentInstance.id);
if (student) {
Object.assign(student, { studentInstance });
}
} catch (error) {
throw new Error('Error Occurred');
}
return student;
}
async delete(studentId) {
try {
const studentIndex = this.students.findIndex(x => x.id === studentId);
if (studentIndex !== -1) {
this.students.splice(studentIndex, 1);
}
} catch (error) {
throw new Error('Error Occurred');
}
return true;
}
async getById(studentId) {
let student;
try {
const id = parseInt(studentId);
student = this.students.find(x => x.id === id);
} catch (err) {
throw new Error('Error Occurred');
}
return student;
}
async getByEmail(studentEmail) {
let student;
try {
student = this.students.find(x => x.email === studentEmail);
} catch (err) {
throw new Error('Error Occurred');
}
return student;
}
async getAll() {
return this.students;
}
async addEnrollment(studentId, enrollment) {
const id = parseInt(studentId);
const student = this.students.find(x => x.id === id);
if (!student) {
throw new Error('student does not exist');
}
if (!student.enrollments) {
student.enrollments = [];
}
student.enrollments.push(enrollment);
return student;
}
};