Skip to content

Commit

Permalink
compiled to javascript
Browse files Browse the repository at this point in the history
  • Loading branch information
Elijah-trillionz committed Jul 21, 2022
1 parent 61321b6 commit b4b8490
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 117 deletions.
167 changes: 85 additions & 82 deletions dist/database.js
Original file line number Diff line number Diff line change
@@ -1,112 +1,108 @@
import * as fs from 'fs/promises';
import * as fsSync from 'fs';
import { instanceOfNodeError } from './error';
import * as fs from "fs/promises";
import * as fsSync from "fs";
import { instanceOfNodeError } from "./error";
class JSONDB {
constructor(dataName) {
// helper functions
// find an object from data
// will return the first data if no key/value is provided
this.filter = (keys, values, cb) => {
const found = this.data[this.dataName].filter((item) => {
let isFound = true;
keys.forEach((key, index) => {
// console.log(item[key], values[index]);
if (item[key] !== values[index]) {
isFound = false;
}
});
console.log(isFound);
return isFound;
});
if (found.length >= 1) {
return cb(null, found);
}
return cb({
message: "Object does not exist in your data",
error: "NOT_FOUND",
errorCode: 612,
}, found);
};
// use this function in each method to validate data is an object only in javascript
this.validateData = (data, cb) => {
if (typeof data === "object" && !Array.isArray(data)) {
return cb(null);
}
return cb({
message: "Data must be an object",
error: "INVALID_TYPE",
errorCode: 611,
});
};
const existingData = getExistingData(dataName);
this.data = existingData ? existingData : { [dataName]: [] };
this.dataName = dataName;
this.schema = {};
}
// get the whole data in d document
get allData() {
return new Promise(async (resolve) => {
resolve(this.data);
});
}
// creating a schema for the data, could you work on the schema
createSchema(schema) {
this.schema = schema;
}
// creating data === add data to the document
create(data) {
return new Promise(async (resolve, reject) => {
this.data[this.dataName].push(data);
await this.updateJSONFile();
resolve('done');
``;
return new Promise((resolve, reject) => {
this.validateData(data, async (err) => {
if (err)
return reject(err);
this.data[this.dataName].push(data);
await this.updateJSONFile();
resolve("done");
});
});
}
// find object with the key value
findOne(filter) {
return new Promise((resolve, reject) => {
const keys = Object.keys(filter);
const values = Object.values(filter);
if (keys.length === values.length) {
const found = this.data[this.dataName].find((item) => {
let isFound = true;
keys.forEach((key, index) => {
if (item[key] !== values[index]) {
isFound = false;
}
});
return isFound;
this.validateData(filter, (err) => {
if (err)
return reject(err);
const keys = Object.keys(filter);
const values = Object.values(filter);
this.filter(keys, values, (err, foundData) => {
// resolve with an empty object if not found, useful for updating
if (err && err.error === "NOT_FOUND")
return resolve({});
resolve(foundData[0]);
});
resolve(found);
}
else {
reject('no key');
}
});
});
}
// find all objects with a key value
findAll(filter) {
findMany(filter) {
return new Promise((resolve, reject) => {
const keys = Object.keys(filter);
const values = Object.values(filter);
if (keys.length === values.length) {
const found = this.data[this.dataName].filter((item) => {
let isFound = true;
keys.forEach((key, index) => {
if (item[key] !== values[index]) {
isFound = false;
}
});
return isFound;
this.validateData(filter, (err) => {
if (err)
return reject(err);
const keys = Object.keys(filter);
const values = Object.values(filter);
this.filter(keys, values, (err, foundData) => {
// resolve with an empty array if not found, useful for updating
if (err && err.error === "NOT_FOUND")
return resolve([]);
resolve(foundData);
});
resolve(found);
}
else {
// indicates filter is not an object
reject('filter needs to be an object');
}
});
}
// update object values with new values
// both filter and newData has to be an object
findOneAndUpdate(filter, newData) {
return new Promise(async (resolve, reject) => {
const oldData = await this.findOne(filter);
if (typeof oldData !== 'string') {
const result = await this.update(oldData, newData);
resolve(result);
}
else {
reject(undefined);
}
});
}
// update many
updateMany(filter, newData) {
return new Promise(async (resolve, reject) => {
const occurrences = await this.findAll(filter);
if (Array.isArray(occurrences)) {
occurrences.forEach(async (oldData) => {
const result = await this.update(oldData, newData);
resolve(result);
});
}
else {
reject(undefined);
}
});
}
// delete
delete(filter) {
return new Promise((resolve, reject) => {
setTimeout(async () => { }, 500);
});
});
}
// helper functions
// private
async updateJSONFile() {
await fs.writeFile(`data/${this.dataName}.json`, JSON.stringify(this.data), {
flag: 'w',
flag: "w",
});
}
async update(oldData, newData) {
Expand All @@ -117,18 +113,17 @@ class JSONDB {
oldData[key] = values[index] ? values[index] : oldData[key];
});
await this.updateJSONFile();
return 'done';
return "done";
}
}
// TODO: how to make a class method private
function getExistingData(dataName) {
try {
const data = fsSync.readFileSync(`data/${dataName}.json`);
return JSON.parse(data.toString());
}
catch (e) {
if (instanceOfNodeError(e, TypeError)) {
if (e.code === 'ENOENT') {
if (e.code === "ENOENT") {
const initialData = { [dataName]: [] };
fsSync.writeFileSync(`data/${dataName}.json`, JSON.stringify(initialData));
return initialData;
Expand All @@ -137,3 +132,11 @@ function getExistingData(dataName) {
}
}
export default JSONDB;
// ERROR CODES: not all are errors, you could say REJECT CODES, where the reject function is used::
// 611: invalid data type - a core error when submitting a data that isn't an object
// 612: not found - when the filter method finds no occurrences
// TODOS:
// validate file is written successfully, else return error
// hide the private methods in JavaScript
// incrementing/decrementing numbers in an object like { name: 'John', age: 21 }
// pushing and popping to an array in an object like { name: 'John', friends: ['James', 'Ken'] }
47 changes: 12 additions & 35 deletions dist/server.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import JSONDB from './database';
const users = new JSONDB('users');
import JSONDB from "./database";
const users = new JSONDB("users");
// backend programmer
async function addNewUser() {
try {
// await proUsers.create({
// id: 1,
// name: 'Elijah',
// username: 'elijahtrillionz',
// });
// getAllUsers();
await users.create({
name: "Starboy",
username: "starsboys",
id: 1,
likes: [1, 2, 3, 4],
});
getAllUsers();
// findAUser();
// updateAUser();
// deleteAUser();
Expand All @@ -17,44 +18,20 @@ async function addNewUser() {
console.log(err);
}
}
// addNewUser();
async function getAllUsers() {
const response = await users.allData;
console.log(response);
}
async function findAUser() {
const name = 'James Spader 1';
const name = "James Spader 1";
const username = undefined;
try {
const response = await users.updateMany({
username: 'elijahtrillionz',
}, ['{ age: 21 }']);
const response = await users.findMany({ name: "Elijah" });
console.log(response);
}
catch (err) {
console.log(err);
}
}
findAUser();
async function updateAUser() {
try {
const response = await users.findOneAndUpdate({ name: 'same' }, {
username: 'johnny',
name: 'Starboy',
});
// console.log(response);
await getAllUsers();
}
catch (err) {
console.log(err);
}
}
async function deleteAUser() {
try {
const response = await users.delete({ id: 1 });
console.log(response);
}
catch (err) {
console.log(err);
}
}
// addNewUser();

0 comments on commit b4b8490

Please sign in to comment.