ezobjects
Advanced tools
Comparing version 2.3.3 to 2.4.0
const docket = require('docket-parser'); | ||
docket.title(`EZ Objects v2.3.3`); | ||
docket.title(`EZ Objects v2.4.0`); | ||
docket.linkClass('text-success'); | ||
docket.parseFiles(['index.js', 'mysql-connection.js']); | ||
docket.generateDocs('docs'); |
75
index.js
@@ -0,1 +1,5 @@ | ||
/** Require external modules */ | ||
const url = require('url'); | ||
/** Require local modules */ | ||
const mysqlConnection = require('./mysql-connection'); | ||
@@ -409,5 +413,21 @@ | ||
/** Create MySQL insert method on prototype */ | ||
parent[obj.className].prototype.insert = async function (db) { | ||
parent[obj.className].prototype.insert = async function (arg1) { | ||
/** Provide option for inserting record from browser if developer implements ajax backend */ | ||
if ( typeof window !== 'undefined' && typeof arg1 == 'string' ) { | ||
const url = new URL(arg1); | ||
const result = await $.get({ | ||
url: url.href, | ||
data: JSON.stringify(this), | ||
dataType: 'json' | ||
}); | ||
if ( result && result.insertId ) | ||
this.id(result.insertId); | ||
else | ||
throw new Error(`${obj.className}.insert(): Unable to insert record, invalid response from remote host.`); | ||
} | ||
/** If the argument is a valid database, insert record into database and capture ID */ | ||
if ( typeof db == 'object' && db.constructor.name == 'MySQLConnection' ) { | ||
else if ( typeof arg1 == 'object' && arg1.constructor.name == 'MySQLConnection' ) { | ||
/** Create array for storing values to insert */ | ||
@@ -492,3 +512,3 @@ const params = []; | ||
/** Execute query to add record to database */ | ||
const result = await db.query(query, params); | ||
const result = await arg1.query(query, params); | ||
@@ -501,3 +521,3 @@ /** Store the resulting insert ID */ | ||
else { | ||
throw new TypeError(`${this.constructor.name}.insert(${typeof db}): Invalid signature.`); | ||
throw new TypeError(`${this.constructor.name}.insert(${typeof arg1}): Invalid signature.`); | ||
} | ||
@@ -510,5 +530,20 @@ | ||
/** Create MySQL load method on prototype */ | ||
parent[obj.className].prototype.load = async function (arg1, arg2) { | ||
parent[obj.className].prototype.load = async function (arg1, arg2) { | ||
/** Provide option for loading record from browser if developer implements ajax backend */ | ||
if ( typeof window !== 'undefined' && typeof arg1 == 'string' ) { | ||
const url = new URL(arg1); | ||
const result = await $.get({ | ||
url: url.href, | ||
dataType: 'json' | ||
}); | ||
if ( result ) | ||
this.init(result); | ||
else | ||
throw new Error(`${obj.className}.load(): Unable to load record, invalid response from remote host.`); | ||
} | ||
/** If the first argument is a valid database and the second is a number, load record from database by ID */ | ||
if ( typeof arg1 == 'object' && arg1.constructor.name == 'MySQLConnection' && typeof arg2 == 'number' ) { | ||
else if ( typeof arg1 == 'object' && arg1.constructor.name == 'MySQLConnection' && ( typeof arg2 == 'number' || ( typeof arg2 == 'string' && typeof obj.stringSearchField == 'string' ) ) ) { | ||
/** Begin SELECT query */ | ||
@@ -538,3 +573,7 @@ let query = `SELECT `; | ||
query += ` FROM ${obj.tableName} `; | ||
query += `WHERE id = ?`; | ||
if ( typeof arg2 === 'string' && typeof obj.stringSearchField === 'string' ) | ||
query += `WHERE ${obj.stringSearchField} = ?`; | ||
else | ||
query += `WHERE id = ?`; | ||
@@ -595,5 +634,19 @@ /** Execute query to load record properties from the database */ | ||
/** Create MySQL update method on prototype */ | ||
parent[obj.className].prototype.update = async function (db) { | ||
parent[obj.className].prototype.update = async function (arg1) { | ||
/** Provide option for inserting record from browser if developer implements ajax backend */ | ||
if ( typeof window !== 'undefined' && typeof arg1 == 'string' ) { | ||
const url = new URL(arg1); | ||
const result = await $.get({ | ||
url: url.href, | ||
data: JSON.stringify(this), | ||
dataType: 'json' | ||
}); | ||
if ( !result ) | ||
throw new Error(`${obj.className}.update(): Unable to update record, invalid response from remote host.`); | ||
} | ||
/** If the argument is a valid database, update database record */ | ||
if ( typeof db == 'object' && db.constructor.name == 'MySQLConnection' ) { | ||
else if ( typeof arg1 == 'object' && arg1.constructor.name == 'MySQLConnection' ) { | ||
/** Create array for storing values to update */ | ||
@@ -655,3 +708,3 @@ const params = []; | ||
/** Execute query to update record in database */ | ||
await db.query(query, params); | ||
await arg1.query(query, params); | ||
} | ||
@@ -661,3 +714,3 @@ | ||
else { | ||
throw new TypeError(`${this.constructor.name}.update(${typeof db}): Invalid signature.`); | ||
throw new TypeError(`${this.constructor.name}.update(${typeof arg1}): Invalid signature.`); | ||
} | ||
@@ -664,0 +717,0 @@ |
{ | ||
"name": "ezobjects", | ||
"version": "2.3.3", | ||
"version": "2.4.0", | ||
"description": "Easy dynamic object generation with optional MySQL table linking", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
173
README.md
@@ -1,2 +0,2 @@ | ||
# EZ Objects v2.3.3 | ||
# EZ Objects v2.4.0 | ||
@@ -23,2 +23,43 @@ EZ Objects is a Node.js module (that can also be usefully browserify'd) that aims to save you lots of time | ||
/** | ||
* There now exists a class called DatabaseRecord which has the following signatures: | ||
* | ||
* @signature new DatabaseRecord([data]) | ||
* @param data PlainObject | ||
* @description Create a new DatabaseRecord object and initialize using either defaults | ||
* or any provided key/value pairs in the plain object `data`. Keys can either be equal | ||
* to the name of a property, or they can be have an underscore before the name of a | ||
* property, as would be the case if you were to JSON.stringify() and then JSON.parse() | ||
* an EZ Object. This allows for easy transferability in cases where JSON is used as | ||
* the transfer medium. | ||
* | ||
* @signature new DatabaseRecord([data]) | ||
* @param data string | ||
* @description Create a new DatabaseRecord object and initialize using either defaults | ||
* or any provided key/value pairs in the JSON encoded string `data`. Keys can either | ||
* be equal to the name of a property, or they can be have an underscore before the name | ||
* of a property, as would be the case if you were to JSON.stringify() an EZ Object. This | ||
* allows for easy transferability in cases where JSON is used as the transfer medium. | ||
* | ||
* @signature init([data]) | ||
* @param data PlainObject | ||
* @description Initialize this object using either defaults or any provided key/value | ||
* pairs in the plain object `data`. This is also the method used by the constructor. | ||
* | ||
* In addition, each property you define will have a single method that is a getter and setter, and it | ||
* will have the following signatures: | ||
* | ||
* @signature myProperty() | ||
* @returns mixed | ||
* @description Get the value of the property. | ||
* | ||
* @signature myProperty(value) | ||
* @param value mixed | ||
* @throws TypeError if `value` is not of the correct javascript data type for myProperty | ||
* @returns this | ||
* @description Set the value of the property, throwing an error if the javascript data type | ||
* does not match the configuration, this is how the strict typing is implemented. This | ||
* signature returns `this` to allow for set call chaining. | ||
*/ | ||
const record = new DatabaseRecord(); | ||
@@ -36,4 +77,7 @@ ``` | ||
**Importing Note:** You must have a unique integer property named `id` to be able to use the MySQL | ||
functionality of EZ Objects. | ||
```javascript | ||
const ezobjects = require('ezobjects'); | ||
const ezobjects = require('./index'); | ||
const fs = require('fs'); | ||
@@ -64,3 +108,3 @@ const moment = require('moment'); | ||
* Configure a new EZ Object called DatabaseRecord with one 'id' | ||
* property that contains extended MySQL configuration settings. | ||
* property that contains additional MySQL configuration settings. | ||
*/ | ||
@@ -81,16 +125,29 @@ const configDatabaseRecord = { | ||
/** Create the DatabaseRecord object */ | ||
/** | ||
* Create the DatabaseRecord object -- Note: This object is not | ||
* linked to a MySQL table directory, and therefore has no tableName | ||
* property, but it has the MySQL configuration properties on `id` because | ||
* it will be extended by a class that is linked to a MySQL table and | ||
* therefore it will need the MySQL configuration of the `id` property. | ||
*/ | ||
ezobjects.createObject(configDatabaseRecord); | ||
/** | ||
* Configure a new EZ Object called Person that extends from the | ||
* Configure a new EZ Object called User that extends from the | ||
* DatabaseRecord object and adds several additional properties and | ||
* a MySQL index. | ||
*/ | ||
const configPerson = { | ||
tableName: 'people', | ||
className: 'Person', | ||
const configUser = { | ||
tableName: 'users', | ||
className: 'User', | ||
extends: DatabaseRecord, | ||
extendsConfig: configDatabaseRecord, | ||
stringSearchField: 'username', | ||
properties: [ | ||
{ | ||
name: 'username', | ||
type: 'string', | ||
mysqlType: 'varchar', | ||
length: 20 | ||
}, | ||
{ | ||
@@ -119,3 +176,3 @@ name: 'firstName', | ||
saveTransform: x => x.join(','), | ||
loadTransform: x => x.split(',') | ||
loadTransform: x => x.split(',').map(x => parseInt(x)) | ||
}, | ||
@@ -135,7 +192,54 @@ { | ||
/** Create the Person object */ | ||
ezobjects.createObject(configPerson); | ||
/** Create the User object */ | ||
ezobjects.createObject(configUser); | ||
/** Create new person, initializing with object passed to constructor */ | ||
const person = new Person({ | ||
/** | ||
* The User object has all of the signatures listed in the comments for | ||
* Basic Example above, but also has the following signatures added since | ||
* it has a tableName defined: | ||
* | ||
* @signature delete(db) | ||
* @param db MySQLConnection | ||
* @description Delete the record in database `db`, table `tableName`, that | ||
* has its `id` field equal to the `id` property of this object. | ||
* | ||
* @signature insert(db) | ||
* @param db MySQLConnection | ||
* @description Insert this object's property values into the database `db`, | ||
* table `tableName`, and store the resulting insertId in the `id` property | ||
* of this object. | ||
* | ||
* @signature load(db, id) | ||
* @param db MySQLConnection | ||
* @param id number The value of the `id` property of the record you wish to load | ||
* @description Load the record in database `db`, table `tableName`, that has | ||
* its `id` field equal to provided `id` parameter. | ||
* | ||
* @signature load(db, fieldValue) | ||
* @param db MySQLConnection | ||
* @param fieldValue mixed The value of the `stringSearchField` property of the | ||
* record you wish to load | ||
* @description Load the record in database `db`, table `tableName`, that has | ||
* its `stringSearchField` field equal to provided `id` parameter. Here, the | ||
* actual field name of `stringSearchField` is provided in the object | ||
* configuration, see the more detailed specifications below. | ||
* | ||
* @signature load(url) | ||
* @param url The URL of a back-end that provides JSON data compatible with this | ||
* object's initializer | ||
* @description Load the JSON-encoded data obtained from `url` using this object's | ||
* initializer. This signature is useful only when your classes are standalone | ||
* browserify'd and requires you to implement a backend at `url` that will output | ||
* the JSON. This signature requires you have jQuery loaded prior to use. | ||
* | ||
* @signature update(db) | ||
* @param db MySQLConnection | ||
* @description Update the record in database `db`, table `tableName`, with its | ||
* `id` field equal to the `id` property of this object, using this object's | ||
* property values. | ||
*/ | ||
/** Create new user, initializing with object passed to constructor */ | ||
const user = new User({ | ||
username: 'richlowe', | ||
firstName: 'Rich', | ||
@@ -151,9 +255,9 @@ lastName: 'Lowe', | ||
/** Create table if it doesn't already exist */ | ||
await ezobjects.createTable(db, configPerson); | ||
await ezobjects.createTable(db, configUser); | ||
/** Insert person into the database */ | ||
await person.insert(db); | ||
/** Insert user into the database */ | ||
await user.insert(db); | ||
/** Log person (should have automatically incremented ID now) */ | ||
console.log(person); | ||
/** Log user (should have automatically incremented ID now) */ | ||
console.log(user); | ||
@@ -168,4 +272,5 @@ /** Close database connection */ | ||
``` | ||
Person { | ||
User { | ||
_id: 1, | ||
_username: 'richlowe', | ||
_firstName: 'Rich', | ||
@@ -178,8 +283,9 @@ _lastName: 'Lowe', | ||
In this snippet, we've created two classes, DatabaseRecord and Person. Person extends DatabaseRecord and is also associated with | ||
a MySQL table called `people`. Each property is given a JavaScript `type` and a MySQL `mysqlType`. Additional MySQL property | ||
In this snippet, we've created two classes, DatabaseRecord and User. User extends DatabaseRecord and is also associated with | ||
a MySQL table called `users`. Each property is given a JavaScript `type` and a MySQL `mysqlType`. Additional MySQL property | ||
configuration options can be provided, which are outlined in more detail below. A BTREE index is also added on the lastName column | ||
for faster searching. While not required, the moment library is used to help translate date formats between MySQL and JavaScript. | ||
for faster searching by lastName. While not required, the moment library is used to help translate date formats between MySQL | ||
and JavaScript. | ||
Since the Person class configuration provided a `tableName` property, it will automatically have additional methods created that are | ||
Since the User class configuration provided a `tableName` property, it will automatically have additional methods created that are | ||
not present in a basic EZ Object. The additional methods are delete(db), insert(db), load(db, id), and update(db). These methods can | ||
@@ -195,3 +301,3 @@ be used to delete the MySQL record corresponding to the object, insert the object properties as a new MySQL record, load a MySQL record | ||
```javascript | ||
const a = new Person(); | ||
const a = new User(); | ||
@@ -204,3 +310,3 @@ console.log(a); | ||
``` | ||
Person { | ||
User { | ||
_id: 0, | ||
@@ -217,3 +323,3 @@ _firstName: '', | ||
```javascript | ||
const b = new Person({ | ||
const b = new User({ | ||
id: 1, | ||
@@ -233,3 +339,3 @@ firstName: 'Rich', | ||
``` | ||
Person { | ||
User { | ||
_id: 1, | ||
@@ -246,3 +352,3 @@ _firstName: 'Rich', | ||
```javascript | ||
const c = new Person(); | ||
const c = new User(); | ||
@@ -262,3 +368,3 @@ c.id(2); | ||
``` | ||
Person { | ||
User { | ||
_id: 2, | ||
@@ -315,2 +421,3 @@ _firstName: 'Bert', | ||
* extendsConfig - object - (optional) The EZ Object configuration for the object that is being extended from [required to extend object] | ||
* stringSearchField - string (optional) The name of a unique property of type `string` that you want to be able to load with as an alternative to `id` | ||
* properties - Array - (required) An array of properties that the object (and MySQL table, if applicable) should contain | ||
@@ -350,1 +457,9 @@ * indexes - Array - (optional) An array of indexes that should be created in the MySQL table, if applicable | ||
* invisible - boolean - (optional) Indicates the index should be invisible | ||
### Default intiailizations for different JavaScript types | ||
* number - 0 | ||
* string - '' | ||
* boolean - false | ||
* Array - [] | ||
* anything else - null |
Sorry, the diff of this file is not supported yet
385046
14
2305
449
2