@azhou/basemodel
v1.0.0
Published
Basic CRUD functions of data model
Downloads
3
Readme
Usage
Initialization
var model = require("@azhou/basemodel")(tableName, fields);
where tableName
is the name of the data table and fields
refers to the field list, either using comma connected string or array.
Example:
// Initialize database
var db = require("@azhou/mysql-wrapper");
db.init("server", "database", "username", "password");
// Create basic CRUD data model
var model = require("@azhou/basemodel")("table", [ "field1", "field2", "field3", ... ]);
Notice when defining fields, id
should not implicitly added and should not be contained in the field list
If validation is required, function validate()
that returns boolean can be added to model
:
model.validate = function (source) { ... }
CRUD Functions
Create Object
model.create(source)
source
is the source object
Example:
model.create({ name: 'John Doe', value: 123.456 }).then(function (id) { ... });
Read Object by ID
model.getById(id, fields)
fields
is optional, which is an array of field list you want to return in the result. If missing or incorrect type, default field list is used.
Examples:
model.getById(123).then(function (obj) { ... });
model.getById(456, [ "name", "value" ]).then(function (obj) { ... });
Read Object by Name
model.getByName(name, fields)
fields
is optional, which is an array of field list you want to return in the result. If missing or incorrect type, default field list is used.
Read All Objects
model.getAll(fields, orderby)
fields
is optional, which is an array of field list you want to return in the result. If missing or incorrect type, default field list is used.orderby
is an optional string argument which defines the ordering of the returned list.
Examples:
model.getAll("name").then(function (list) { ... });
model.getAll([ "name", "value" ]).then(function (list) { ... });
model.getAll([ "name", "value" ], "name DESC").then(function (list) { ... });
Read Objects by ID list
There are four different of formats:
Read all objects whose
id
is in theids
list:model.getAllByIds(ids)
Read all objects whose
id
is in theids
list, and returns the fields listed infields
arraymodel.getAllByIds(ids, fields)
Object array is provided, and the
id
is retrieved from fieldnameOfIdField
model.getAllByIds(objects, nameOfIdField)
Object array is provided, and the
id
is retrieved from fieldnameOfIdField
. Field array is also providedmodel.getAllByIds(objects, nameOfIdField, fields)
Examples:
model.getAllByIds([ 1, 2, 3 ]).then(function (list) { ... });
model.getAllByIds([ 1, 2, 3 ], [ "name", "value" ]).then(function (list) { ... });
model.getAllByIds(objects, "id").then(function (list) { ... });
model.getAllByIds(objects, "id", [ "name", "value" ]).then(function (list) { ... });
Update Object
model.update(id, source)
Example:
model.update(123, { name: "Mike Smith" }).then(function () { ... });
Delete Object
model.delete(id)