Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Node Clean Architecture - Frameworks - InMemoryStudentRepository.js
const StudentRepository = require('../../../application/contracts/StudentRepository');
module.exports = class InMemoryStudentRepository extends StudentRepository {
constructor() {
super();
this.students = [];
this.currentId = 1;
}
add(studentInstance) {
return new Promise((resolve, reject) => {
try {
this.currentId = this.currentId + 1;
studentInstance.id = this.currentId;
this.students.push(studentInstance);
resolve(studentInstance);
} catch (error) {
reject(new Error('Error Occurred'));
}
});
}
update(studentInstance) {
return new Promise((resolve, reject) => {
try {
const student = this.students.find(x => x.id === studentInstance.id);
if (student) {
Object.assign(student, { studentInstance });
}
resolve(student);
} catch (error) {
reject(new Error('Error Occurred'));
}
});
}
delete(studentId) {
return new Promise((resolve, reject) => {
try {
const studentIndex = this.students.findIndex(x => x.id === studentId);
if (studentIndex !== -1) {
this.students.splice(studentIndex, 1);
}
resolve(true);
} catch (error) {
reject(new Error('Error Occurred'));
}
});
}
getById(studentId) {
return new Promise((resolve, reject) => {
try {
const id = parseInt(studentId);
const student = this.students.find(x => x.id === id);
resolve(student);
} catch (err) {
reject(new Error('Error Occurred'));
}
});
}
getByEmail(studentEmail) {
return new Promise((resolve, reject) => {
try {
const student = this.students.find(x => x.email === studentEmail);
resolve(student);
} catch (err) {
reject(new Error('Error Occurred'));
}
});
}
getAll() {
return new Promise((resolve, reject) => {
resolve(this.students);
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment