Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update api.js #3

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 15 additions & 31 deletions routes/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,18 @@ function readStoreJSON() {
}
readStoreJSON();

// write into json
function writeStoreJson(store) {
fs.writeFile(
"./db/store.json",
JSON.stringify(store, null, 4),
"utf8",
function cb(err) {
if (err) {
}
}
);
}
// Helper functions

/**
Expand Down Expand Up @@ -215,18 +227,8 @@ router.post("/:entityType", (req, res) => {
let newEntity = req.body;
newEntity["id"] = id;
entities.push(newEntity);

fs.writeFile(
"./db/store.json",
JSON.stringify(store, null, 4),
"utf8",
function cb(err) {
if (err) {
res.status(500).send("Could not save data");
}
}
);
res.send(newEntity);
writeFileJson(store);
});
// Update an existing entity rowby id
router.put("/:entityType/:id", (req, res) => {
Expand All @@ -250,15 +252,7 @@ router.put("/:entityType/:id", (req, res) => {
obj.id === mergedEntity.id ? mergedEntity : obj
);

fs.writeFile(
"./db/store.json",
JSON.stringify(store, null, 4),
"utf8",
function cb(err) {
if (err) {
}
}
);
writeFileJson(store);
res.send(mergedEntity);
});

Expand All @@ -268,17 +262,7 @@ router.delete("/:entityType/:id", (req, res) => {
let id = req.params.id;
if (removeEntityById(store, entityType, id) != -1) {
res.send("Deleted Successfully");

fs.writeFile(
"./db/store.json",
JSON.stringify(store, null, 4),
"utf8",
function cb(err) {
if (err) {
res.status(500).send("Could not save data");
}
}
);
writeStoreJson(store);
} else {
respondWith404(res);
}
Expand Down