Skip to content

Commit

Permalink
create fetch push set and query_db
Browse files Browse the repository at this point in the history
  • Loading branch information
reashetyrr committed Feb 25, 2020
1 parent 90a5bd3 commit c8f89d2
Show file tree
Hide file tree
Showing 7 changed files with 253 additions and 9 deletions.
13 changes: 13 additions & 0 deletions dbutils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = {
query_database: query_db
};

async function query_db(connection, query, params) {
return new Promise((resolve, reject) => {
connection.query(query, params, (err, results) => {
if (err)
return reject(err);
return resolve(results);
});
});
}
131 changes: 123 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ let connection;
const methods = {
fetch: require('lib/fetch.js'),
set: require('lib/set.js'),
add: require('lib/add.js'),
subtract: require('lib/subtract.js'),
// add: require('lib/add.js'),
// subtract: require('lib/subtract.js'),
push: require('lib/push.js'),
delete: require('lib/delete.js'),
has: require('lib/has.js'),
all: require('lib/all.js'),
type: require('lib/type')
// delete: require('lib/delete.js'),
// has: require('lib/has.js'),
// all: require('lib/all.js'),
// type: require('lib/type')
};

function init_connection(config) {
Expand Down Expand Up @@ -62,7 +62,122 @@ module.exports = {
version: '1.0.0',
init: init_connection,
fetch: (key, ops) => {
if (!key) throw new TypeError('No key specified. Need Help? Check Out: discord.gg/plexidev');
if (!key) throw new TypeError('No key specified');
return arbitrate('fetch', {id: key, ops: ops || {}});
}
},
get: function(key, ops) {
if (!key) throw new TypeError('No key specified');
return arbitrate('fetch', {id: key, ops: ops || {}});
},

/**
* This function sets new data based on a key in the database.
* @param {key} input any string as a key. Also allows for dot notation following the key.
* @param {options} [input={ target: null }] Any options to be added to the request.
* @returns {data} the updated data.
*/

set: function(key, value, ops) {
if (!key) throw new TypeError('No key specified');
if (value === undefined) throw new TypeError('No value specified');
return arbitrate('set', {stringify: true, id: key, data: value, ops: ops || {}});
},

/**
* This function adds a number to a key in the database. (If no existing number, it will add to 0)
* @param {key} input any string as a key. Also allows for dot notation following the key.
* @param {options} [input={ target: null }] Any options to be added to the request.
* @returns {data} the updated data.
*/

add: function(key, value, ops) {
if (!key) throw new TypeError('No key specified');
if (isNaN(value)) throw new TypeError('Must specify value to add');
return arbitrate('add', {id: key, data: value, ops: ops || {}});
},

/**
* This function subtracts a number to a key in the database. (If no existing number, it will subtract from 0)
* @param {key} input any string as a key. Also allows for dot notation following the key.
* @param {options} [input={ target: null }] Any options to be added to the request.
* @returns {data} the updated data.
*/

subtract: function(key, value, ops) {
if (!key) throw new TypeError('No key specified');
if (isNaN(value)) throw new TypeError('Must specify value to add');
return arbitrate('subtract', {id: key, data: value, ops: ops || {}});
},

/**
* This function will push into an array in the database based on the key. (If no existing array, it will create one)
* @param {key} input any string as a key. Also allows for dot notation following the key.
* @param {options} [input={ target: null }] Any options to be added to the request.
* @returns {data} the updated data.
*/

push: function(key, value, ops) {
if (!key) throw new TypeError('No key specified');
if (!value && value != 0) throw new TypeError('Must specify value to push');
return arbitrate('push', {stringify: true, id: key, data: value, ops: ops || {}});
},


/**
*/

/**
* This function will delete an object (or property) in the database.
* @param {key} input any string as a key. Also allows for dot notation following the key, this will delete the prop in the object.
* @param {options} [input={ target: null }] Any options to be added to the request.
* @returns {boolean} if it was a success or not.
*/

delete: function(key, ops) {
if (!key) throw new TypeError('No key specified');
return arbitrate('delete', {id: key, ops: ops || {}});
},

/**
* This function returns a boolean indicating whether an element with the specified key exists or not.
* @param {key} input any string as a key. Also allows for dot notation following the key, this will return if the prop exists or not.
* @param {options} [input={ target: null }] Any options to be added to the request.
* @returns {boolean} if it exists.
*/

has: function(key, ops) {
if (!key) throw new TypeError('No key specified');
return arbitrate('has', {id: key, ops: ops || {}});
},

includes: function(key, ops) {
if (!key) throw new TypeError('No key specified');
return arbitrate('has', {id: key, ops: ops || {}});
},

/**
* This function fetches the entire active table
* @param {options} [input={ target: null }] Any options to be added to the request.
* @returns {boolean} if it exists.
*/

all: function(ops) {
return arbitrate('all', {ops: ops || {}});
},

fetchAll: function(ops) {
return arbitrate('all', {ops: ops || {}});
},


/*
* Used to get the type of the value.
*/


type: function(key, ops) {
if (!key) throw new TypeError('No key specified');
return arbitrate('type', {id: key, ops: ops || {}});
},
};
20 changes: 20 additions & 0 deletions lib/fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Require Packages
const get = require('lodash/get');
const query_db = require('dbutils').query_database;

module.exports = async function(connection, params, options) {
// Fetch Entry
let fetched = await query_db(connection, `SELECT * FROM ${options.table} WHERE ID = (?)`, [params.id]);
if (!fetched) return null; // If empty, return null
fetched = JSON.parse(fetched.json);
try {
fetched = JSON.parse(fetched)
} catch (e) {}

// Check if target was supplied
if (params.ops.target)
fetched = get(fetched, params.ops.target); // Get prop using dot notation

// Return data
return fetched;
};
52 changes: 52 additions & 0 deletions lib/push.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Require Packages
const get = require('lodash/get');
const set = require('lodash/set');
const query_db = require('dbutils').query_database;

module.exports = async function(connection, params, options) {

// Fetch entry
let fetched = await query_db(connection,`SELECT * FROM ${options.table} WHERE ID = (?)`, [params.id]);

// If not found, create empty row
if (!fetched) {
await query_db(connection, `INSERT INTO ${options.table} (ID,json) VALUES (?,?)`, [params.id, '{}']);
fetched = await query_db(connection,`SELECT * FROM ${options.table} WHERE ID = (?)`,[params.id]);
}

// Check if a target was supplied
if (params.ops.target) {
fetched = JSON.parse(fetched.json);
try { fetched = JSON.parse(fetched) } catch (e) {}
params.data = JSON.parse(params.data);
if (typeof fetched !== 'object') throw new TypeError('Cannot push into a non-object.');
let oldArray = get(fetched, params.ops.target);
if (oldArray === undefined) oldArray = [];
else if (!Array.isArray(oldArray)) throw new TypeError('Target is not an array.');
oldArray.push(params.data);
params.data = set(fetched, params.ops.target, oldArray);
} else {
if (fetched.json === '{}') fetched.json = [];
else fetched.json = JSON.parse(fetched.json);
try { fetched.json = JSON.parse(fetched.json) } catch (e) {}
params.data = JSON.parse(params.data);
if (!Array.isArray(fetched.json)) throw new TypeError('Target is not an array.');
fetched.json.push(params.data);
params.data = fetched.json;
}

// Stringify data
params.data = JSON.stringify(params.data);

// Update entry with new data
await query_db(connection, `UPDATE ${options.table} SET json = (?) WHERE ID = (?)`, [params.data, params.id]);

// Fetch & return new data
let newData = await query_db(connection, `SELECT * FROM ${options.table} WHERE ID = (?)`, [params.id]).json;
if (newData === '{}') return null;
else {
newData = JSON.parse(newData);
try { newData = JSON.parse(newData) } catch (e) {}
return newData
}
};
38 changes: 38 additions & 0 deletions lib/set.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const set = require('lodash/set');
const query_db = require('dbutils').query_database;

module.exports = async function(connection, params, options) {
// Fetch entry
let fetched = await query_db(connection, `SELECT * FROM ${options.table} WHERE ID = (?)`, [params.id]);

// If not found, create empty row
if (!fetched) {
await query_db(connection, `INSERT INTO ${options.table} (ID,json) VALUES (?,?)`, [params.id, '{}']);
fetched = await query_db(connection, `SELECT * FROM ${options.table} WHERE ID = (?)`, [params.id]);
}

// Parse fetched
fetched = JSON.parse(fetched.json);
try { fetched = JSON.parse(fetched) } catch (e) {}

// Check if a target was supplied
if (typeof fetched === 'object' && params.ops.target) {
params.data = JSON.parse(params.data);
params.data = set(fetched, params.ops.target, params.data);
} else if (params.ops.target) throw new TypeError('Cannot target a non-object.');

// Stringify data
params.data = JSON.stringify(params.data);

// Update entry with new data
await query_db(connection, `UPDATE ${options.table} SET json = (?) WHERE ID = (?)`, [params.data, params.id]);

// Fetch & return new data
let newData = await query_db(connection, `SELECT * FROM ${options.table} WHERE ID = (?)`, [params.id]).json;
if (newData === '{}') return null;
else {
newData = JSON.parse(newData);
try { newData = JSON.parse(newData) } catch (e) {}
return newData
}
};
7 changes: 6 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"author": "Reashetyr",
"license": "MIT",
"dependencies": {
"lodash": "^4.17.15",
"mysql": "^2.18.1"
},
"repository": {
Expand Down

0 comments on commit c8f89d2

Please sign in to comment.