Security News
PyPI’s New Archival Feature Closes a Major Security Gap
PyPI now allows maintainers to archive projects, improving security and helping users make informed decisions about their dependencies.
ezobjects-mysql
Advanced tools
EZ Objects (MySQL Edition) is a Node.js module (that can also be usefully browserify'd) that aims to save you lots of time writing class objects that are strictly typed in JavaScript, and can be tied directly to MySQL database tables by way of a mix of insert/update/load/delete class method signatures. All you have to do is create simple class configurations for each of your objects and then create them using the createClass() function.
EZ Object's capabilities has been split into multiple packages to target the needs of specific users. This
is a branch of the original ezobjects
module that preserves the original MySQL table-linked capability,
while the original ezobjects
has had it removed so those who don't need the database storage can remove
the dependency. It also worked out better that way so that ezobjects
types can be different than MySQL
types, which might be different from another database's types, etc. If you don't need MySQL capability,
you can find the original ezobjects
package on npm or GitHub.
npm install --save ezobjects-mysql
Important Notes: Each of your EZ Object tables must include an int
or integer
property named
id
that will be automatically configured to serve as an auto-incrementing primary index in the MySQL
table that you are linking your object to. The load
method will generally be based off hte id
field,
unless you specify a stringSearchField
. Also note that ou must also use EZ Object's MySQLConnection class
for your database connection for compatability purposes and to allow async/await functionality.
const ezobjects = require(`ezobjects-mysql`);
const fs = require(`fs`);
/**
* Load external MySQL configuration which uses the following JSON
* format:
* {
* "host" : "localhost",
* "user" : "ezobjects",
* "password" : "myPassword",
* "database" : "ezobjects"
* }
*/
const configMySQL = JSON.parse(fs.readFileSync(`mysql-config.json`));
/**
* Create a connection object for the MySQL database using our MySQL
* module async/await wrapper.
*/
const db = new ezobjects.MySQLConnection(configMySQL);
/**
* Configure a new EZ Object called DatabaseRecord with the required
* `id` property that will serve as the auto-incrementing primary index.
*/
const configDatabaseRecord = {
className: `DatabaseRecord`,
properties: [
{ name: `id`, type: `int` }
]
};
/**
* Create the DatabaseRecord object -- Note: This object is not linked
* to a MySQL table directly, as it has no `tableName` property, but
* it can be extended by EZ Objects that are linked to tables.
*/
ezobjects.createClass(configDatabaseRecord);
/**
* Configure a new EZ Object called UserAccount that extends from the
* DatabaseRecord object and adds several additional properties,
* including an array of `int` property and a MySQL index.
*/
const configUserAccount = {
tableName: `user_accounts`,
className: `UserAccount`,
extends: DatabaseRecord,
extendsConfig: configDatabaseRecord,
properties: [
{ name: `username`, type: `varchar`, length: 20 },
{ name: `firstName`, type: `varchar`, length: 20 },
{ name: `lastName`, type: `varchar`, length: 20 },
{ name: `checkingBalance`, type: `decimal`, length: 17, decimals: 2 },
{ name: `permissions`, type: `Array`, arrayOf: { type: 'int' } },
{ name: `favoriteDay`, type: `date` }
],
indexes: [
{ name: `username`, type: `BTREE`, columns: [ `username` ] }
]
};
/** Create the UserAccount object */
ezobjects.createClass(configUserAccount);
/**
* Create a new UserAccount called `userAccount`, initializing with
* plain object passed to constructor.
*/
const userAccount = new UserAccount({
username: `richlowe`,
firstName: `Rich`,
lastName: `Lowe`,
checkingBalance: 4.32,
permissions: [1, 3, 5],
favoriteDay: new Date(`01-01-2018`)
});
/**
* Test if `userAccount` is an instance of DatabaseRecord using
* the included `instanceOf` helper function.
*/
console.log(ezobjects.instanceOf(userAccount, `DatabaseRecord`));
/** Let's use a self-executing async wrapper so we can await results */
(async () => {
try {
/** Create `user_accounts` table if it doesn`t already exist */
await ezobjects.createTable(configUserAccount, db);
/** Insert `userAccount` into the database */
await userAccount.insert(db);
/** Log `userAccount` (should have automatically incremented ID now) */
console.log(userAccount);
/** Capture ID of new record */
const id = userAccount.id();
/** Change the property values a bit */
userAccount.checkingBalance(50.27);
userAccount.firstName(`Richard`);
userAccount.favoriteDay(new Date(`09-01-2019`));
/** Update `userAccount` in the database */
await userAccount.update(db);
/** Log `userAccount` (should have `checkingBalance` of 50.27) */
console.log(userAccount);
/** Create another new UserAccount called `anotherUserAccount` */
const anotherUserAccount = new UserAccount();
/**
* Using the ID captured from the previous insert operation, load
* the record from database.
*/
await anotherUserAccount.load(id, db);
/** Log `anotherUserAccount` (should match last `userAccount`) */
console.log(anotherUserAccount);
/** Delete `anotherUserAccount` from the database */
await anotherUserAccount.delete(db);
} catch ( err ) {
/** Cleanly log any errors */
console.log(err.message);
} finally {
/** Close database connection */
db.close();
}
})();
true
UserAccount {
_id: 1,
_username: 'richlowe',
_firstName: 'Rich',
_lastName: 'Lowe',
_checkingBalance: 4.32,
_permissions: [ 1, 3, 5 ],
_favoriteDay: 2018-01-01T06:00:00.000Z }
UserAccount {
_id: 1,
_username: 'richlowe',
_firstName: 'Richard',
_lastName: 'Lowe',
_checkingBalance: 50.27,
_permissions: [ 1, 3, 5 ],
_favoriteDay: 2019-09-01T05:00:00.000Z }
UserAccount {
_id: 1,
_username: 'richlowe',
_firstName: 'Richard',
_lastName: 'Lowe',
_checkingBalance: 50.27,
_permissions: [ 1, 3, 5 ],
_favoriteDay: 2019-09-01T05:00:00.000Z }
These are the object method signatures even the most basic of EZ Objects will have:
PlainObject
- (optional)data
. Keys can either be equal to the name of a property, or they can 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.string
- (optional)data
. Keys can either be equal to the name of a property, or they can 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.PlainObject
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:
mixed
mixed
TypeError
if value
is not of the correct javascript data type for myPropertythis
to allow for set call chaining.These are the object method signatures that will additionally be provided if your configuration contains a tableName
,
meaning it's intended to be linked to a MySQL table:
MySQLConnection
db
, table tableName
, that has its id
field equal to the id
property of this object.MySQLConnection
db
, table tableName
, and store the resulting insertId in the id
property of this object.RowDataPacket
A MySQL RowDataPacket
returned as part of a MySQL result setMySQLConnection
mysqlRow
. You can optionally pass the database db
if you need it to be provided as a third argument to any loadTransform methods on configured properties.MySQLConnection
obj
. You can optionally pass the database db
if you need it to be provided as a third argument to any loadTransform methods on configured properties.id
property of the record you wish to loadMySQLConnection
db
, table tableName
, that has its id
field equal to provided id
parameter.mixed
- The value of the otherSearchField
property of the record you wish to loadMySQLConnection
db
, table tableName
, that has its otherSearchField
field equal to provided fieldValue
parameter. Here, the actual field name of otherSearchField
is provided in the object configuration, see the configuration section below.string
- The URL of a back-end that provides JSON data compatible with this object's initializerMySQLConnection
url
. You can optionally pass the database db
if you need it to be provided as a third argument to any loadTransform methods on configured properties.url
that will output the JSON. This signature also requires you have jQuery loaded prior to use.MySQLConnection
db
, table tableName
, with its id
field equal to the id
property of this object, using this object's property values.The EZ Objects module exports two functions and a MySQL class object:
A function that creates a MySQL table corresponding to the configuration outlined in objectConfig
, if it doesn't already exist
A function that creates an ES6 class corresponding to the configuration outlined in objectConfig
, with constructor, initializer, getters, setters, and also delete, insert, load, and update if tableName
is configured
A MySQL database connection class that wraps the standard mysql object and provides it with async/await functionality and transaction helpers
See the following for how to configure your EZ Objects:
string
- (required) Name of the classArray
- (optional) An array of property configurations that the object (and MySQL table, if applicable) should have corresponding properties formixed
- (optional) The object that the new object should be extended from [required to extend object]object
- (optional) The EZ Object configuration for the object that is being extended from [required to extend object]Array
- (optional) An array of MySQL index configurations that should be created in the MySQL tablestring
- (optional) Provide if object should be linked with MySQL database tablestring
- (optional) The name of a unique property of type string
that you want to be able to load with as an alternative to id
string
- (required) Name of the property, must conform to both JavaScript and MySQL rulesstring
- (optional) EZ Object type that the property must be equal to -- types can be bit
, tinyint
, smallint
, mediumint
, int
, integer
, bigint
, real
, double
, float
, decimal
, numeric
, date
, time
,
timestamp
, datetime
, year
, char
, varchar
, binary
, varbinary
, tinyblob
, blob
, mediumblob
, longblob
, tinytext
,
text
, mediumtext
, longtext
, enum
, set
, boolean
, function
, object
, any other valid object constructor name, or array
where arrayOf
is provided with information about the array element types. [either type or instanceOf is required]string
- (optional) JavaScript class constructor name that the property must be an instance of [either type or instanceOf is required]mixed
- (optional) Sets the default value for the property in the class objectboolean
- (optional) Indicates the property can be null, default is that only plain objects and custom object types are nullableobject
- (required for type array
) A plain object containing he EZ Object type
or instanceOf
of the elements of the array -- types can be bit
, tinyint
, smallint
, mediumint
, int
, integer
, bigint
, real
, double
, float
, decimal
, numeric
, date
, time
,
timestamp
, datetime
, year
, char
, varchar
, binary
, varbinary
, tinyblob
, blob
, mediumblob
, longblob
, tinytext
,
text
, mediumtext
, longtext
, enum
, set
, boolean
, function
, object
, or any other valid object constructor name (which can alternatively be used with instanceOf
instead). [either type or instanceOf is required]function
- (optional) Function that transforms and returns the property value prior to setting. The handler for this transform will be passed the expected value type
, if needed.number
- (optional) MySQL data length for the property [required for some data types like VARCHAR, optional for others where it's used to determine displayed precision on SELECT'ed data types like FLOAT]number
- (optional) Number of decimals that should be provided for certain data types when SELECT'ed from the MySQL tableboolean
- (optional) Indicates the property is a UNIQUE KEY in the MySQL tableboolean
- (optional) Indicates the property should be unsigned in the MySQL tableboolean
- (optional) Indicates the property should be zero-filled in the MySQL tablestring
- (optional) Indicates the property should note the provided comment in the MySQL tablestring
- (optional) Indicates the property should use the provided charset in the MySQL tablestring
- (optional) Indicates the property should use the provided collation in the MySQL tableboolean
- (optional) Indicates the property should be auto-incremented in the MySQL tablefunction
- (optional) Function that transforms and returns the property value prior to saving in the databasefunction
- (optional) Function that transforms and returns the property value after loading from the database. The handler for this transform will be passed the expected value type
, if needed, along with the MySQL connection db
if it was provided as the third argument of the object's load
method.string
- (required) Name of the index, can be arbitrary, but must be unique and not PRIMARYArray
- (required) An array of strings containing property names to be indexedstring
- (optional) Index type, can be BTREE or HASH, defaults to BTREEnumber
- (optional) Indicates the index should use the provided key block sizestring
- (optional) Indicates the index should use the provided parserboolean
- (optional) Indicates the index should be visibleboolean
- (optional) Indicates the index should be invisiblebit
- Buffer.from([])
tinyint
- 0
smallint
- 0
mediumint
- 0
int
- 0
integer
- 0
bigint
- 0
real
- 0
double
- 0
float
- 0
decimal
- 0
numeric
- 0
date
- new Date(0)
time
- 00:00:00
timestamp
- ``datetime
- new Date(0)
year
- 0
char
- ``varchar
- ``binary
- Buffer.from([])
varbinary
- Buffer.from([])
tinyblob
- Buffer.from([])
blob
- Buffer.from([])
mediumblob
- Buffer.from([])
longblob
- Buffer.from([])
tinytext
- ``text
- ``mediumtext
- ``longtext
- ``enum
- ``set
- new Set()
boolean
- false
function
- function () { }
object
- {}
array
types - []
null
Please open an issue on the GitHub repository if you find any broken functionality or other bugs/errors. Feature requests will also be accepted, but are not guaranteed to be implemented.
MIT Licensed
FAQs
Easy dynamic object generation with optional MySQL table linking
The npm package ezobjects-mysql receives a total of 11 weekly downloads. As such, ezobjects-mysql popularity was classified as not popular.
We found that ezobjects-mysql demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now allows maintainers to archive projects, improving security and helping users make informed decisions about their dependencies.
Research
Security News
Malicious npm package postcss-optimizer delivers BeaverTail malware, targeting developer systems; similarities to past campaigns suggest a North Korean connection.
Security News
CISA's KEV data is now on GitHub, offering easier access, API integration, commit history tracking, and automated updates for security teams and researchers.