northwind-rest-api
Version:
Local REST API Exposing 'Northwind Traders' Database.
61 lines (55 loc) • 2.35 kB
JavaScript
const dal = require("../data-access-layer/dal");
const imageHelper = require("../helpers/image-helper");
async function getAllEmployees() {
const employees = await dal.getAllEmployees();
return employees;
};
async function getOneEmployee(id) {
const employees = await dal.getAllEmployees();
const employee = employees.find(e => e.id === id);
return employee;
};
async function addEmployee(employee, image) {
const employees = await dal.getAllEmployees();
const maxId = employees.reduce((maxId, e) => e.id > maxId ? e.id : maxId, 0);
employee.id = maxId + 1;
const fileName = await imageHelper.saveEmployeeImage(image);
employee.imageUrl = fileName ? "http://localhost:3030/api/employees/images/" + fileName : null;
employees.push(employee);
await dal.saveAllEmployees(employees);
return employee;
};
async function updateEmployee(newEmployee, image) {
const employees = await dal.getAllEmployees();
const existingEmployee = employees.find(e => e.id === newEmployee.id);
if (!existingEmployee) return null;
for (const prop in newEmployee) {
if (newEmployee[prop] !== undefined) {
existingEmployee[prop] = newEmployee[prop];
}
}
const currentFileName = existingEmployee.imageUrl ? existingEmployee.imageUrl.substring(existingEmployee.imageUrl.lastIndexOf("/") + 1) : null;
const newFileName = await imageHelper.updateEmployeeImage(currentFileName, image);
if(newFileName) {
existingEmployee.imageUrl = "http://localhost:3030/api/employees/images/" + newFileName;
}
await dal.saveAllEmployees(employees);
return existingEmployee;
};
async function deleteEmployee(id) {
const employees = await dal.getAllEmployees();
const index = employees.findIndex(e => e.id === id);
if (index === -1) return;
const existingEmployee = employees[index];
const currentFileName = existingEmployee.imageUrl ? existingEmployee.imageUrl.substring(existingEmployee.imageUrl.lastIndexOf("/") + 1) : null;
await imageHelper.deleteEmployeeImage(currentFileName)
employees.splice(index, 1);
await dal.saveAllEmployees(employees);
};
module.exports = {
getAllEmployees,
getOneEmployee,
addEmployee,
updateEmployee,
deleteEmployee
};