UNPKG

northwind-rest-api

Version:

Local REST API Exposing 'Northwind Traders' Database.

61 lines (55 loc) 2.35 kB
const dal = require("../data-access-layer/dal"); const imageHelper = require("../helpers/image-helper"); async function getAllSuppliers() { const suppliers = await dal.getAllSuppliers(); return suppliers; }; async function getOneSupplier(id) { const suppliers = await dal.getAllSuppliers(); const supplier = suppliers.find(s => s.id === id); return supplier; }; async function addSupplier(supplier, image) { const suppliers = await dal.getAllSuppliers(); const maxId = suppliers.reduce((maxId, s) => s.id > maxId ? s.id : maxId, 0); supplier.id = maxId + 1; const fileName = await imageHelper.saveSupplierImage(image); supplier.imageUrl = fileName ? "http://localhost:3030/api/suppliers/images/" + fileName : null; suppliers.push(supplier); await dal.saveAllSuppliers(suppliers); return supplier; }; async function updateSupplier(newSupplier, image) { const suppliers = await dal.getAllSuppliers(); const existingSupplier = suppliers.find(s => s.id === newSupplier.id); if (!existingSupplier) return null; for (const prop in newSupplier) { if (newSupplier[prop] !== undefined) { existingSupplier[prop] = newSupplier[prop]; } } const currentFileName = existingSupplier.imageUrl ? existingSupplier.imageUrl.substring(existingSupplier.imageUrl.lastIndexOf("/") + 1) : null; const newFileName = await imageHelper.updateSupplierImage(currentFileName, image); if(newFileName) { existingSupplier.imageUrl = "http://localhost:3030/api/suppliers/images/" + newFileName; } await dal.saveAllSuppliers(suppliers); return existingSupplier; }; async function deleteSupplier(id) { const suppliers = await dal.getAllSuppliers(); const index = suppliers.findIndex(s => s.id === id); if (index === -1) return; const existingSupplier = suppliers[index]; const currentFileName = existingSupplier.imageUrl ? existingSupplier.imageUrl.substring(existingSupplier.imageUrl.lastIndexOf("/") + 1) : null; await imageHelper.deleteSupplierImage(currentFileName) suppliers.splice(index, 1); await dal.saveAllSuppliers(suppliers); }; module.exports = { getAllSuppliers, getOneSupplier, addSupplier, updateSupplier, deleteSupplier };