Skip to content

Commit

Permalink
included and tested the updateMany method
Browse files Browse the repository at this point in the history
  • Loading branch information
Elijah-trillionz committed Aug 1, 2022
1 parent 58e504a commit a841f00
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 3 deletions.
37 changes: 35 additions & 2 deletions src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ class JSONDB {
});
}

this.validateData(oldData, async (err: ErrorObj) => {
this.validateData(newData, async (err: ErrorObj) => {
if (err) return reject(err);

await this.update(oldData, newData, (err: ErrorObj) => {
Expand All @@ -151,6 +151,39 @@ class JSONDB {
});
}

updateMany(filter: Object, newData: Object) {
return new Promise(async (resolve, reject) => {
try {
const oldData = await this.findMany(filter);

if (oldData.length < 1) {
return reject({
message: "No data was found to be updated",
errorCode: 612,
error: "NOT_FOUND",
});
}

this.validateData(newData, async (err: ErrorObj) => {
if (err) return reject(err);

oldData.forEach((value) => {
(async () => {
await this.update(value, newData, (err: ErrorObj) => {
if (err) return reject(err);

resolve("Done");
});
})();
});
});
} catch (e) {
// for errors thrown when the findMany method encounters an error
reject(e);
}
});
}

// helper functions

// find an object from data
Expand Down Expand Up @@ -222,7 +255,7 @@ class JSONDB {
}

// validate schema: used in the update and the create method
validateSchema = (data: Object, cb: Function) => {
private validateSchema = (data: Object, cb: Function) => {
const valid = this.validate(data);
if (!valid) {
const { keyword, params, message } = this.validate.errors[0];
Expand Down
18 changes: 17 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ async function addNewUser() {
console.log(err);
}
}
addNewUser();
// addNewUser();

async function getAllUsers() {
const response = await users.allData;
Expand All @@ -68,3 +68,19 @@ async function updateUser() {
}
}
// updateUser();

async function updateMany() {
try {
const res = await users.updateMany(
{ username: "starsboys" },
{
likes: [{ id: 1 }],
age: 10,
}
);
console.log(res);
} catch (e) {
console.log(e);
}
}
updateMany();

0 comments on commit a841f00

Please sign in to comment.