@abeai/node-utils 中文文档教程
node-utils
Current Benchmarks (11/27/19)
MacBook Pro (15-inch, 2018) v10.15 (19A603)
2.6 GHz 6-Core Intel Core i7
32 GB 2400 MHz DDR4
┌────────────────────────┬─────────────────────────────┬────────────────────────────────┐
│ Name │ Node-Utils │ Old │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Get-Lodash │ 4234345 ops/s | +422.22% │ 810835 ops/s | x5.22 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Set-Lodash │ 3179749 ops/s | +527.10% │ 507055 ops/s | x6.27 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ toPath-Lodash │ 578923 ops/s | +157.54% │ 224788 ops/s | x2.58 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ isObject-Lodash │ 925387752 ops/s | +0.10% │ 924506336 ops/s | x1.00 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ snakeCase-Lodash │ 11846262 ops/s | +353.94% │ 2609630 ops/s | x4.54 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ camelCase-Lodash │ 7228157 ops/s | +272.86% │ 1938551 ops/s | x3.73 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ kebabCase-Lodash │ 10954872 ops/s | +327.54% │ 2562305 ops/s | x4.28 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Mapkeys-Lodash │ 4058951 ops/s | +590.54% │ 587798 ops/s | x6.91 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Mapkeys-AltMap │ 4163350 ops/s | +149.15% │ 1671015 ops/s | x2.49 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ ForEach-Lodash │ 33148953 ops/s | +3170.51% │ 1013571 ops/s | x32.71 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Debounce-Lodash │ 453294 ops/s | +50.37% │ 301450 ops/s | x1.50 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Clone-Lodash │ 204591656 ops/s | +1276.91% │ 14858709 ops/s | x13.77 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ CloneDeep-Lodash │ 1447731 ops/s | +180.19% │ 516701 ops/s | x2.80 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Request-RequestPromise │ 7593 ops/s | +1443.29% │ 492 ops/s | x15.43 slower │
└────────────────────────┴─────────────────────────────┴────────────────────────────────┘
Documentation
Classes
- Timer
计时器类,用于保持准确的秒表时间。
- PGActiveModel ⇐
PGEncryptModel
从中扩展自定义模型的 Postgres 活动模型类。
- PGBaseModel
从中扩展自定义模型的 Postgres 基本模型类。
- PGConnecter
Postgres Connecter 初始化单例连接。
- PGEncryptModel ⇐
PGBaseModel
从中扩展自定义模型的 Postgres 加密模型类。
Constants
- PGTypes
Postgres 模型的字段类型。
Functions
- camelCase(str) ⇒
String
将
string
转换为 驼峰式大小写。- cloneDeep(value) ⇒
*
此方法类似于
clone
,只是它递归地克隆value
。- cloneDeepWith(value, [cb]) ⇒
*
此方法类似于
cloneWith
,只是它递归地克隆value
。- merge(object, [...sources]) ⇒
Object
此方法类似于
assign
,只是它递归地合并自己的和 将源对象的可枚举字符串键控属性继承到 目标对象。 解析为undefined
的源属性是 如果目标值存在则跳过。 数组和普通对象属性 被递归合并。 其他对象和值类型被覆盖 任务。 源对象从左到右应用。 随后的 来源覆盖以前来源的属性分配。注意:此方法会改变
对象
。- debounce(func, delay) ⇒
function
创建一个延迟调用
func
直到wait
之后的去抖函数 自上次 debounced 函数被执行以来已经过去了毫秒数 调用。 debounced函数自带一个cancel
方法来取消 延迟的func
调用和立即调用它们的flush
方法。 提供options
以指示是否应在上调用func
wait
超时的前沿和/或后沿。func
被调用 将最后一个参数提供给去抖函数。 随后的 对去抖动函数的调用返回最后一个func
的结果 调用。注意:如果
leading
和trailing
选项是true
,func
是 仅当去抖函数时在超时的后沿调用 在wait
超时期间被多次调用。如果
wait
为0
且leading
为false
,则延迟func
调用 直到下一个滴答声,类似于setTimeout
,超时为0
。请参阅 David Corbacho 的文章 有关
_.debounce
和_.throttle
之间差异的详细信息。- forEach(collection, cb) ⇒
Array
|Object
迭代
collection
的元素并为每个元素调用iteratee
。 使用三个参数调用 iteratee:(value, index|key, collection)。 Iteratee 函数可以通过显式返回false
提前退出迭代。- get(object, path, [defaultReturn]) ⇒
*
获取
object
的path
处的值。 如果解析值是undefined
,返回defaultValue
。- isEmpty(value) ⇒
boolean
检查
value
是否为空对象或数组如果对象没有自己的可枚举字符串键,则对象被认为是空的 特性。
- isObject(value) ⇒
boolean
检查
value
是否是 语言类型对象
。 (例如数组、函数、对象、正则表达式、new Number(0)
和new String('')
)- kebabCase(str) ⇒
String
将
string
转换为 烤肉串。- keysToCamel(o) ⇒
String
将 Object 的键从 snake、kebab 和 space case 转换为 驼峰式大小写。
- mapKeys(object, iteratee) ⇒
Object
这个方法创建一个对象 与
object
相同的值和通过运行每个自己的可枚举生成的键object
到iteratee
的字符串键控属性。 迭代器被调用 有两个参数:(值,键)。- request(options) ⇒
Promise
向给定的 url 发出 HTTP/S 请求。
- set(object, path, value) ⇒
Object
在
object
的path
处设置值。 如果path
的一部分不存在, 它被创建了。 数组是为缺失的索引属性创建的,而对象 为所有其他缺失的属性创建。注意:此方法会改变
对象
。- snakeCase(str) ⇒
String
将
string
转换为 蛇案。- toPath(value) ⇒
Array
将
value
转换为属性路径数组。
Timer
计时器类,用于保持准确的秒表时间。
Kind:全局类
new Timer(startTime, totalTime)
构造一个 Timer 实例。
返回:Timer
- 返回新的 Timer 实例。
Param | Type | Default | Description |
---|---|---|---|
startTime | BigInt | 0 | the time the Timer started at. |
totalTime | BigInt | 0 | the total time the Timer elapsed. |
timer.start() ⇒ Timer
启动秒表
Kind:Timer
的实例方法
返回:Timer
- 返回它自己。
timer.stop() ⇒ Timer
停止秒表
Kind:Timer
的实例方法
返回:Timer
- 返回它自己。
timer.ns() ⇒ Number
获取经过的时间(以纳秒为单位)。
Kind:Timer
的实例方法 返回:Number
- ns.
timer.us() ⇒ Number
获取经过的时间(以微秒为单位)。
Kind:Timer
的实例方法 退货:编号
- 我们。
timer.ms() ⇒ Number
获取经过的时间(以毫秒为单位)。
Kind:Timer
的实例方法 退货:编号
- 女士。
PGActiveModel ⇐ PGEncryptModel
从中扩展自定义模型的 Postgres 活动模型类。
种类:全局类
扩展:PGEncryptModel
- PGActiveModel ⇐
PGEncryptModel
- instance
- static
- .create(model) ⇒
PGActiveModel
- .findById(id) ⇒
PGActiveModel
- .findLimtedBy(fieldValues, operator, limit) ⇒
Array.<PGActiveModel>
- .findAllBy(fieldValues, operator) ⇒
Array.<PGActiveModel>
- .findAll() ⇒
Array.<PGActiveModel>
- .deleteById(id) ⇒
PGActiveModel
- .deleteLimitedBy(fieldValues, operator, limit) ⇒
Array.<PGActiveModel>
- .deleteAllBy(fieldValues, operator) ⇒
Array.<PGActiveModel>
- .deleteAll() ⇒
Array.<PGActiveModel>
- .updateById(id, model, returnModel) ⇒
PGActiveModel
- .updateLimitedBy(fieldValues, model, operator, returnModel, limit) ⇒
Array.<PGActiveModel>
- .updateAllBy(fieldValues, model, operator, returnModel) ⇒
Array.<PGActiveModel>
- .updateAll(model) ⇒
Array.<PGActiveModel>
- .create(model) ⇒
pgActiveModel.addProperty(name, value)
向该模型添加一个属性从数据库的角度来看,这不会影响它。
Kind:PGActiveModel
的实例方法
Param | Type | Description |
---|---|---|
name | String | The name of the property. |
value | Any | The the value to set the property. |
pgActiveModel.find() ⇒ PGActiveModel
检索当前通过其设置字段类型为 PGTypes.PK
的模型
Kind:PGActiveModel
的实例方法
返回:PGActiveModel
- 返回它自己。
pgActiveModel.delete() ⇒ PGActiveModel
通过PGTypes.PK
类型的集合字段删除当前模型
Kind: PGActiveModel
返回:PGActiveModel
- 返回它自己。
pgActiveModel.create() ⇒ PGActiveModel
使用当前设置的属性创建一个新行。
Kind:PGActiveModel
的实例方法 返回:PGActiveModel
- 返回它自己。
pgActiveModel.save() ⇒ PGActiveModel
保存模型及其更改的属性。
Kind:PGActiveModel
的实例方法 返回:PGActiveModel
- 返回它自己。
pgActiveModel.update() ⇒ PGActiveModel
使用传入的更改属性更新模型。
Kind:PGActiveModel
的实例方法 返回:PGActiveModel
- 返回它自己。
pgActiveModel.decrypt(…props) ⇒ PGActiveModel
根据将字符串名称作为参数传入模型来解密模型的属性。
Kind:PGActiveModel
的实例方法 返回:PGActiveModel
- 返回它自己。
Param | Type | Description |
---|---|---|
…props | String | name of each property. |
pgActiveModel.encrypt(…props) ⇒ PGActiveModel
根据将字符串名称作为参数传入的模型属性加密。
Kind:PGActiveModel
的实例方法 返回:PGActiveModel
- 返回它自己。
Param | Type | Description |
---|---|---|
…props | String | name of each property. |
pgActiveModel.redactSensitiveData(redactionCensor) ⇒ PGActiveModel
编辑模型中的所有加密字段。
Kind:PGActiveModel
的实例方法 返回:PGActiveModel
- 返回它自己。
Param | Type | Default | Description |
---|---|---|---|
redactionCensor | String | "[redacted]" | The string to replace the encrypted values with. |
pgActiveModel.getEncryptedProfile() ⇒ String
获取模型设置的加密配置文件。
Kind:PGActiveModel
的实例方法 返回:String
- 返回它本身。
PGActiveModel.create(model) ⇒ PGActiveModel
使用传入的属性和值创建一个新行。
种类:PGActiveModel
的静态方法 返回:PGActiveModel
- 返回它自己。
Param | Type | Description |
---|---|---|
model | Object | A plain object with the name of the properties and their values to be set with the new model. |
示例
create({
username: 'foo',
email: 'test@test.com',
});
PGActiveModel.findById(id) ⇒ PGActiveModel
通过 PK 检索模型。
种类:PGActiveModel
的静态方法 返回:PGActiveModel
- 返回一个新模型。
Param | Type | Description |
---|---|---|
id | String | The PK of the model to retrieve. |
PGActiveModel.findLimtedBy(fieldValues, operator, limit) ⇒ Array.<PGActiveModel>
通过传入的 fieldValues
检索有限数量的模型。
种类:PGActiveModel
的静态方法 返回:Array.<PGActiveModel>
- 返回一组新模型。
Param | Type | Default | Description |
---|---|---|---|
fieldValues | Object | A plain object with the properties and their values to retrive by. | |
operator | String | AND | The query operator to use between each of the fieldValues [AND , OR , 'NOT'] |
limit | Number | The limit to stop searching when the records retrived are equal or greater than the set limit . |
示例
findLimtedBy({
username: ['user2', 'OR', 'user3'],
email: null,
}, 'AND', 5);
PGActiveModel.findAllBy(fieldValues, operator) ⇒ Array.<PGActiveModel>
通过传入的字段值检索所有模型。 当检索到的记录等于或大于 limit
时将停止搜索。
种类:PGActiveModel
的静态方法 返回:Array.<PGActiveModel>
- 返回一组新模型。
Param | Type | Default | Description |
---|---|---|---|
fieldValues | Object | A plain object with the properties and their values to retrive by. | |
operator | String | AND | The query operator to use between each of the fieldValues [AND , OR , 'NOT'] |
示例
findAllBy({
username: ['user2', 'OR', 'user3'],
email: null,
}, 'AND');
PGActiveModel.findAll() ⇒ Array.<PGActiveModel>
检索模型表中的所有行。
种类:PGActiveModel
的静态方法 返回:Array.<PGActiveModel>
- 返回一组新模型。
PGActiveModel.deleteById(id) ⇒ PGActiveModel
删除通过 PK 找到的具有传入的 props 和值的模型。
种类:PGActiveModel
的静态方法 返回:PGActiveModel
- 返回一个新模型或 null
Param | Type | Description |
---|---|---|
id | String | The PK of the model to delete. |
PGActiveModel.deleteLimitedBy(fieldValues, operator, limit) ⇒ Array.<PGActiveModel>
通过传入的 fieldValues 删除有限数量的模型。
种类:PGActiveModel
的静态方法 返回:Array.<PGActiveModel>
- 返回已删除模型的数组。
Param | Type | Default | Description |
---|---|---|---|
fieldValues | Object | A plain object with the properties and their values to delete by. | |
operator | String | AND | The query operator to use between each of the fieldValues [AND , OR , 'NOT'] |
limit | Number | The limit to stop deleting when the records retrived are equal or greater than the set limit . |
示例
deleteLimitedBy({
registered: false,
},'AND', 5);
PGActiveModel.deleteAllBy(fieldValues, operator) ⇒ Array.<PGActiveModel>
通过传入的fieldValues
删除所有模型。
种类:PGActiveModel
的静态方法 返回:Array.<PGActiveModel>
- 返回已删除模型的数组。
Param | Type | Default | Description |
---|---|---|---|
fieldValues | Object | A plain object with the properties and their values to delete by. | |
operator | String | AND | The query operator to use between each of the fieldValues [AND , OR , 'NOT'] |
示例
deleteAllBy({
registered: true,
});
PGActiveModel.deleteAll() ⇒ Array.<PGActiveModel>
删除其表中的所有模型。
种类:PGActiveModel
的静态方法 返回:Array.<PGActiveModel>
- 返回已删除模型的数组或 null
PGActiveModel.updateById(id, model, returnModel) ⇒ PGActiveModel
使用传入的属性和值更新 PK 找到的模型。
种类:PGActiveModel
的静态方法 返回:PGActiveModel
- 返回新模型或空
Param | Type | Default | Description |
---|---|---|---|
id | String | The PK of the model to update. | |
model | Object | A plain object with the name of the properties and their values to update the model with. | |
returnModel | Boolean | true | If the updated model should be returned or not. It will return null if this is set to false. |
示例
updateById('09A75A84-A921-4F68-8FEF-B8392E3702C2',
{
password: 'bestpasswordinalltheland12346969420'
});
PGActiveModel.updateLimitedBy(fieldValues, model, operator, returnModel, limit) ⇒ Array.<PGActiveModel>
使用传入的道具和 model
的值更新传入的 fieldValues
找到的模型。
种类:PGActiveModel
的静态方法 返回:Array.<PGActiveModel>
- 返回更新模型的数组或 null
Param | Type | Default | Description |
---|---|---|---|
fieldValues | Object | A plain object with the properties and their values to update by. | |
model | Object | A plain object with the name of the properties and their values to update the model with. | |
operator | String | AND | The query operator to use between each of the fieldValues [AND , OR , 'NOT'] |
returnModel | Boolean | true | If the updated model should be returned or not. It will return null if this is set to false. |
limit | Number | The limit to stop searching when the records retrived are equal or greater than the set limit . |
Example
updateLimitedBy({
password: null
},
{
password: 'bestpasswordinalltheland12346969420'
},'AND', true, 5);
PGActiveModel.updateAllBy(fieldValues, model, operator, returnModel) ⇒ Array.<PGActiveModel>
使用 传入的道具和值更新传入
fieldValues
找到的所有模型型号。
种类:PGActiveModel
的静态方法 返回:Array.<PGActiveModel>
- 返回更新模型的数组或 null
Param | Type | Default | Description |
---|---|---|---|
fieldValues | Object | A plain object with the properties and their values to update by. | |
model | Object | A plain object with the name of the properties and their values to update the model with. | |
operator | String | AND | The query operator to use between each of the fieldValues [AND , OR , 'NOT'] |
returnModel | Boolean | true | If the updated model should be returned or not. It will return null if this is set to false. |
Example
updateAllBy({
password: null
},
{
password: 'bestpasswordinalltheland12346969420'
});
PGActiveModel.updateAll(model) ⇒ Array.<PGActiveModel>
使用传入的属性和 model
的值更新其表中的所有模型。
种类:PGActiveModel
的静态方法 返回:Array.<PGActiveModel>
- 返回更新模型的数组或 null
Param | Type | Description |
---|---|---|
model | Object | A plain object with the name of the properties and their values to update the models with. |
示例
updateAll({
password: 'bestpasswordinalltheland12346969420'
});
PGBaseModel
Postgres 基础模型类,用于扩展自定义模型。
PGConnecter
Postgres Connecter 初始化单例连接。
new PGConnecter(options)
Param | Type | Default | Description |
---|---|---|---|
options | Object | The connection options. | |
options.crypto | Crypto | postgres/crypto/interface.js | The implemented crypto interface that follows postgres/crypto/interface.js |
options.pg | Object | The options object to pass into pg lib. | |
options.pg.user | String | process.env.PGUSER | User's name. |
options.pg.password | String | process.env.PGPASSWORD | User's password. |
options.pg.database | String | process.env.PGDATABASE | Database's name. |
options.pg.port | Number | process.env.PGPORT | Database's port. |
options.pg.connectionString | String | Postgres formated connection string. e.g. postgres://user:password@host:5432/database | |
options.pg.ssl | TLSSocket | Options to be passed into the native Node.js TLSSocket socket. | |
options.pg.types | pg.types | Custom type parsers. See node-postgres types for more details. | |
options.pg.statement_timeout | Number | 0 | Number of milliseconds before a statement in query will time out. |
options.pg.query_timeout | Number | 0 | number of milliseconds before a query call will timeout. |
options.pg.connectionTimeoutMillis | Number | 0 | Number of milliseconds to wait before timing out when connecting a new client. |
options.pg.idleTimeoutMillis | Number | 10000 | Number of milliseconds a client must sit idle in the pool and not be checked out before it is disconnected from the backend and discarded. |
options.pg.max | Number | 10 | Maximum number of clients the pool should contain. |
示例
var pgOptions = {
pg: {
connectionString: 'postgres://postgres@localhost/pgtest',
}
};
try {
pgOptions.crypto = require('@abeai/node-crypto').utils.pgCrypto;
} catch (_) {
console.log(_);
}
var pg = new PGConnecter(pgOptions);
PGEncryptModel ⇐ PGBaseModel
从中扩展自定义模型的 Postgres 加密模型类。
种类:全局类
扩展:PGBaseModel
PGTypes
Postgres 模型的字段类型。
Kind:全局常量
PGTypes.PK
表的主键。
种类:PGTypes
的静态属性
PGTypes.Encrypt
将此字段标记为自动加密/散列(用于查找)但不在检索时自动解密。 该表将需要有一个与此集合字段同名的字段,并以 __
作为前缀。
种类:PGTypes
的静态属性 示例
//if you have an encrypted field called `phone` the sql query for creating the table may look like this
CREATE TABLE IF NOT EXISTS users (
phone VARCHAR (500),
__phone VARCHAR (500) UNIQUE,
);
PGTypes.EncryptWithoutHash
将此字段标记为自动加密但不在检索时自动解密。 与 Encrypt
相同,但没有查找哈希。
种类:PGTypes
的静态属性
PGTypes.EncryptProfile
将此字段标记为使用 aws kms 进行加密/解密/散列的加密配置文件。
种类:PGTypes
的静态属性
PGTypes.AutoCrypt
将此字段标记为自动加密/散列(用于查找)并在检索时自动解密。
种类:PGTypes
的静态属性
PGTypes.AutoCryptWithoutHash
将此字段标记为在检索时自动加密和自动解密。 与 AutoCrypt
相同,但没有查找哈希。
种类:PGTypes
的静态属性
PGTypes.Hash
将此字段标记为在创建时进行哈希处理(即:密码和您要保护的其他信息)
Kind:PGTypes
camelCase(str) ⇒ String
将 string
转换为 驼峰式大小写。
种类:全局函数
返回:String
- 返回驼峰式字符串。
Param | Type | Default | Description |
---|---|---|---|
str | String | '' | The string to convert. |
示例
camelCase('Foo Bar');
// => 'fooBar'
camelCase('--foo-bar--');
// => 'fooBar'
camelCase('__FOO_BAR__');
// => 'fooBar'
cloneDeep(value) ⇒ \*
此方法类似于clone
,只是它递归地克隆value
。
种类:全局函数
返回:\*
- 返回深度克隆值。
Param | Type | Description |
---|---|---|
value | \* | The value to recursively clone. |
示例
var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false
cloneDeepWith(value, [cb]) ⇒ \*
此方法类似于cloneWith
,只是它递归地克隆value
。
种类:全局函数
返回:\*
- 返回深度克隆值。
Param | Type | Description |
---|---|---|
value | \* | The value to recursively clone. |
[cb] | function | The function to customize cloning. |
示例
function customizer(value) {
if (_.isElement(value)) {
return value.cloneNode(true);
}
}
var el = cloneDeepWith(document.body, customizer);
console.log(el === document.body);
// => false
console.log(el.nodeName);
// => 'BODY'
console.log(el.childNodes.length);
// => 20
merge(object, […sources]) ⇒ Object
这个方法类似于assign
除了它递归地合并自己的和 将源对象的可枚举字符串键控属性继承到 目标对象。 解析为 undefined
的源属性是 如果目标值存在则跳过。 数组和普通对象属性 被递归合并。 其他对象和值类型被覆盖 任务。 源对象从左到右应用。 随后的 来源覆盖以前来源的属性分配。
注意:此方法会改变对象
。
种类:全局函数
返回:对象
- 返回对象
。
Param | Type | Description |
---|---|---|
object | Object | The destination object. |
[…sources] | Object | The source objects. |
示例
var object = {
'a': [{ 'b': 2 }, { 'd': 4 }]
};
var other = {
'a': [{ 'c': 3 }, { 'e': 5 }]
};
merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
debounce(func, delay) ⇒ function
创建一个延迟调用 func
直到 wait
之后的去抖函数 自上次 debounced 函数被执行以来已经过去了毫秒数 调用。 debounced函数自带一个cancel
方法来取消 延迟的 func
调用和立即调用它们的 flush
方法。 提供 options
以指示是否应在上调用 func
wait
超时的前沿和/或后沿。 func
被调用 将最后一个参数提供给去抖功能。 随后的 对去抖动函数的调用返回最后一个 func
的结果 调用。
注意:如果leading
和trailing
选项是true
,func
是 仅当去抖函数时在超时的后沿调用 在 wait
超时期间被多次调用。
如果 wait
为 0
且 leading
为 false
,则延迟 func
调用 直到下一个滴答声,类似于 setTimeout
,超时为 0
。
请参阅 David Corbacho 的文章 有关 _.debounce
和 _.throttle
之间差异的详细信息。
种类:全局函数
返回:function
- 返回新的去抖函数。
Param | Type | Default | Description |
---|---|---|---|
func | function | The function to debounce. | |
delay | Number | 0 | The number of milliseconds to delay. |
示例
// Avoid costly calculations while the window size is in flux.
jQuery(window).on('resize', debounce(calculateLayout, 150));
// Invoke `sendMail` when clicked, debouncing subsequent calls.
jQuery(element).on('click', debounce(sendMail, 300, {
'leading': true,
'trailing': false
}));
// Ensure `batchLog` is invoked once after 1 second of debounced calls.
var debounced = debounce(batchLog, 250, { 'maxWait': 1000 });
var source = new EventSource('/stream');
jQuery(source).on('message', debounced);
// Cancel the trailing debounced invocation.
jQuery(window).on('popstate', debounced.cancel);
forEach(collection, cb) ⇒ Array
| Object
迭代collection
的元素并为每个元素调用iteratee
。 使用三个参数调用 iteratee:(value, index|key, collection)。 Iteratee 函数可以通过显式返回 false
提前退出迭代。
种类:全局函数
返回:数组
| 对象
- 返回集合
。
Param | Type | Description |
---|---|---|
collection | Array | Object | The collection to iterate over. |
cb | function | The function invoked per iteration. |
示例
forEach([1, 2], function(value) {
console.log(value);
});
// => Logs `1` then `2`.
forEach({ 'a': 1, 'b': 2 }, function(value, key) {
console.log(key);
});
// => Logs 'a' then 'b' (iteration order is not guaranteed).
get(object, path, [defaultReturn]) ⇒ \*
获取object
的path
处的值。 如果解析值是 undefined
,返回 defaultValue
。
种类:全局函数
返回:\*
- 返回解析后的值。
Param | Type | Description |
---|---|---|
object | Object | The object to query. |
path | Array | The path of the property to get. |
[defaultReturn] | \* | The value returned for undefined resolved values. |
示例
var object = { 'a': [{ 'b': { 'c': 3 } }] };
get(object, 'a[0].b.c');
// => 3
get(object, ['a', '0', 'b', 'c']);
// => 3
isEmpty(value) ⇒ boolean
检查value
是否为空对象或数组
如果对象没有自己的可枚举字符串键,则对象被认为是空的 特性。
种类:全局函数
返回:boolean
- 如果value
为空,则返回true
,否则返回false
。
Param | Type | Description |
---|---|---|
value | \* | The value to check. |
示例
isEmpty({});
// => true
isEmpty([]);
// => true
isEmpty([1, 2, 3]);
// => false
isEmpty({ 'a': 1 });
// => false
isObject(value) ⇒ boolean
检查value
是否是 语言类型 对象
。 (例如数组、函数、对象、正则表达式、new Number(0)
和 new String('')
)
种类:全局函数< br> 返回:boolean
- 如果value
是对象,则返回true
,否则返回false
。
Param | Type | Description |
---|---|---|
value | \* | The value to check. |
示例
isObject({});
// => true
isObject([1, 2, 3]);
// => true
isObject(null);
// => false
kebabCase(str) ⇒ String
将string
转换为 烤肉串。
种类:全局函数
返回:String
- 返回 kebab 大小写的字符串。
Param | Type | Default | Description |
---|---|---|---|
str | String | '' | The string to convert. |
示例
kebabCase('Foo Bar');
// => 'foo-bar'
kebabCase('fooBar');
// => 'foo-bar'
kebabCase('__FOO_BAR__');
// => 'foo-bar'
keysToCamel(o) ⇒ String
将 Object 的键从 snake、kebab 和 space case 转换为 驼峰式大小写。
种类:全局函数
返回:String
- 返回带有驼峰式键的对象。
Param | Type | Description |
---|---|---|
o | Object | The object to convert. |
示例
keysToCamel({foo_bar:{bar_meme:20}})
// => {fooBar:{barMeme:20}}
mapKeys(object, iteratee) ⇒ Object
这个方法创建了一个对象 与 object
相同的值和通过运行每个自己的可枚举生成的键 object
到 iteratee
的字符串键控属性。 迭代器被调用 有两个参数:(值,键)。
种类:全局函数
返回:对象
- 返回新的映射对象。
Param | Type | Description |
---|---|---|
object | Object | The object to iterate over. |
iteratee | function | The function invoked per iteration. |
示例
mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
return key + value;
});
// => { 'a1': 1, 'b2': 2 }
request(options) ⇒ Promise
向给定的 url 发出 HTTP/S 请求。
种类:全局函数
返回:Promise
- 返回已解决或被拒绝的承诺。
Param | Type | Default | Description |
---|---|---|---|
options | Object | Supports all of nodes HTTP/S Module's options + the folloing. | |
options.uri | String | fully qualified uri. | |
options.method | String | GET | http method. |
options.headers | Object | {} | http headers. |
options.qs | Object | object containing querystring values to be appended to the uri . | |
options.simple | Boolean | true | throws an error for any non 2xx status code response. |
options.resolveWithFullResponse | Boolean | false | set to true if the full response object is wanted instead of just the body data. |
options.qs | Object | object containing querystring values to be appended to the uri . | |
options.body | Object | Buffer | String | ReadSteam | entity body for PATCH, POST and PUT requests. Must be a Buffer , String or ReadStream . If json is true, then body must be a JSON-serializable object. | |
options.form | Object | when passed an object or a querystring, this sets body to a querystring representation of value, and adds Content-type: application/x-www-form-urlencoded header . | |
options.json | Boolean | setsbody to JSON representation of value and adds Content-type: application/json header . Additionally, parses the response body as JSON. | |
options.keepAlive | Boolean | true | set to false to turn off keepAlive sockets. |
options.authorization.basic | Object | takes an object with client and secret props to create a Authorization: Basic client:secret base64 header. | |
options.authorization.bearer | String | creates a Authorization: Bearer bearer header. | |
options.redirectMax | Number | 5 | number of times the request will follow a redirect from the server. |
options.logger | Object | the pino logger to log errors. |
示例
await request({
uri: 'http://127.0.0.1:4261/'),
simple: false,
resolveWithFullResponse: true
});
set(object, path, value) ⇒ Object
在object
的path
处设置值。 如果 path
的一部分不存在, 它被创建了。 数组是为缺失的索引属性创建的,而对象 为所有其他缺失的属性创建。
注意:此方法会改变对象
。
种类:全局函数
返回:对象
- 返回对象
。
Param | Type | Description |
---|---|---|
object | Object | The object to modify. |
path | Array | The path of the property to set. |
value | \* | The value to set. |
示例
var object = { 'a': [{ 'b': { 'c': 3 } }] };
set(object, ['x', '0', 'y', 'z'], 5);
console.log(object.x[0].y.z);
// => 5
snakeCase(str) ⇒ String
将string
转换为 蛇案。
种类:全局函数
返回:String
- 返回蛇形字符串。
Param | Type | Default | Description |
---|---|---|---|
str | String | '' | The string to convert. |
示例
snakeCase('Foo Bar');
// => 'foo_bar'
snakeCase('fooBar');
// => 'foo_bar'
snakeCase('--FOO-BAR--');
// => 'foo_bar'
toPath(value) ⇒ Array
将value
转换为属性路径数组。
种类:全局函数
返回:Array
- 返回新的属性路径数组。
Param | Type | Description |
---|---|---|
value | String | The value to convert. |
例子
toPath('a.b.c');
// => ['a', 'b', 'c']
toPath('a[0].b.c');
// => ['a', '0', 'b', 'c']
node-utils
Current Benchmarks (11/27/19)
MacBook Pro (15-inch, 2018) v10.15 (19A603)
2.6 GHz 6-Core Intel Core i7
32 GB 2400 MHz DDR4
┌────────────────────────┬─────────────────────────────┬────────────────────────────────┐
│ Name │ Node-Utils │ Old │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Get-Lodash │ 4234345 ops/s | +422.22% │ 810835 ops/s | x5.22 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Set-Lodash │ 3179749 ops/s | +527.10% │ 507055 ops/s | x6.27 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ toPath-Lodash │ 578923 ops/s | +157.54% │ 224788 ops/s | x2.58 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ isObject-Lodash │ 925387752 ops/s | +0.10% │ 924506336 ops/s | x1.00 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ snakeCase-Lodash │ 11846262 ops/s | +353.94% │ 2609630 ops/s | x4.54 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ camelCase-Lodash │ 7228157 ops/s | +272.86% │ 1938551 ops/s | x3.73 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ kebabCase-Lodash │ 10954872 ops/s | +327.54% │ 2562305 ops/s | x4.28 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Mapkeys-Lodash │ 4058951 ops/s | +590.54% │ 587798 ops/s | x6.91 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Mapkeys-AltMap │ 4163350 ops/s | +149.15% │ 1671015 ops/s | x2.49 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ ForEach-Lodash │ 33148953 ops/s | +3170.51% │ 1013571 ops/s | x32.71 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Debounce-Lodash │ 453294 ops/s | +50.37% │ 301450 ops/s | x1.50 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Clone-Lodash │ 204591656 ops/s | +1276.91% │ 14858709 ops/s | x13.77 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ CloneDeep-Lodash │ 1447731 ops/s | +180.19% │ 516701 ops/s | x2.80 slower │
├────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ Request-RequestPromise │ 7593 ops/s | +1443.29% │ 492 ops/s | x15.43 slower │
└────────────────────────┴─────────────────────────────┴────────────────────────────────┘
Documentation
Classes
- Timer
Timer class for keeping accurate stop watch like time.
- PGActiveModel ⇐
PGEncryptModel
Postgres Active Model class to extend a custom model from.
- PGBaseModel
Postgres Base Model class to extend a custom model from.
- PGConnecter
Postgres Connecter to initialize the singleton for connection.
- PGEncryptModel ⇐
PGBaseModel
Postgres Encryption Model class to extend a custom model from.
Constants
- PGTypes
The types of fields for Postgres Models.
Functions
- camelCase(str) ⇒
String
Converts
string
to camel case.- cloneDeep(value) ⇒
*
This method is like
clone
except that it recursively clonesvalue
.- cloneDeepWith(value, [cb]) ⇒
*
This method is like
cloneWith
except that it recursively clonesvalue
.- merge(object, [...sources]) ⇒
Object
This method is like
assign
except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve toundefined
are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.Note: This method mutates
object
.- debounce(func, delay) ⇒
function
Creates a debounced function that delays invoking
func
until afterwait
milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with acancel
method to cancel delayedfunc
invocations and aflush
method to immediately invoke them. Provideoptions
to indicate whetherfunc
should be invoked on the leading and/or trailing edge of thewait
timeout. Thefunc
is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the lastfunc
invocation.Note: If
leading
andtrailing
options aretrue
,func
is invoked on the trailing edge of the timeout only if the debounced function is invoked more than once during thewait
timeout.If
wait
is0
andleading
isfalse
,func
invocation is deferred until to the next tick, similar tosetTimeout
with a timeout of0
.See David Corbacho's article for details over the differences between
_.debounce
and_.throttle
.- forEach(collection, cb) ⇒
Array
|Object
Iterates over elements of
collection
and invokesiteratee
for each element. The iteratee is invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returningfalse
.- get(object, path, [defaultReturn]) ⇒
*
Gets the value at
path
ofobject
. If the resolved value isundefined
, thedefaultValue
is returned in its place.- isEmpty(value) ⇒
boolean
Checks if
value
is an empty object or arrayObjects are considered empty if they have no own enumerable string keyed properties.
- isObject(value) ⇒
boolean
Checks if
value
is the language type ofObject
. (e.g. arrays, functions, objects, regexes,new Number(0)
, andnew String('')
)- kebabCase(str) ⇒
String
Converts
string
to kebab case.- keysToCamel(o) ⇒
String
Converts Object's keys from snake,kebab and space case to camel case.
- mapKeys(object, iteratee) ⇒
Object
This method creates an object with the same values as
object
and keys generated by running each own enumerable string keyed property ofobject
thruiteratee
. The iteratee is invoked with two arguments: (value, key).- request(options) ⇒
Promise
Makes a HTTP/S Request to a given url.
- set(object, path, value) ⇒
Object
Sets the value at
path
ofobject
. If a portion ofpath
doesn't exist, it's created. Arrays are created for missing index properties while objects are created for all other missing properties.Note: This method mutates
object
.- snakeCase(str) ⇒
String
Converts
string
to snake case.- toPath(value) ⇒
Array
Converts
value
to a property path array.
Timer
Timer class for keeping accurate stop watch like time.
Kind: global class
new Timer(startTime, totalTime)
Constructs a Timer instance.
Returns: Timer
- Returns the new Timer instance.
Param | Type | Default | Description |
---|---|---|---|
startTime | BigInt | 0 | the time the Timer started at. |
totalTime | BigInt | 0 | the total time the Timer elapsed. |
timer.start() ⇒ Timer
Starts the stopwatch
Kind: instance method of Timer
Returns: Timer
- Returns it's self.
timer.stop() ⇒ Timer
Stops the stopwatch
Kind: instance method of Timer
Returns: Timer
- Returns it's self.
timer.ns() ⇒ Number
Gets the elapsed time in nanoseconds.
Kind: instance method of Timer
Returns: Number
- ns.
timer.us() ⇒ Number
Gets the elapsed time in microseconds.
Kind: instance method of Timer
Returns: Number
- us.
timer.ms() ⇒ Number
Gets the elapsed time in millieconds.
Kind: instance method of Timer
Returns: Number
- ms.
PGActiveModel ⇐ PGEncryptModel
Postgres Active Model class to extend a custom model from.
Kind: global class
Extends: PGEncryptModel
- PGActiveModel ⇐
PGEncryptModel
- instance
- static
- .create(model) ⇒
PGActiveModel
- .findById(id) ⇒
PGActiveModel
- .findLimtedBy(fieldValues, operator, limit) ⇒
Array.<PGActiveModel>
- .findAllBy(fieldValues, operator) ⇒
Array.<PGActiveModel>
- .findAll() ⇒
Array.<PGActiveModel>
- .deleteById(id) ⇒
PGActiveModel
- .deleteLimitedBy(fieldValues, operator, limit) ⇒
Array.<PGActiveModel>
- .deleteAllBy(fieldValues, operator) ⇒
Array.<PGActiveModel>
- .deleteAll() ⇒
Array.<PGActiveModel>
- .updateById(id, model, returnModel) ⇒
PGActiveModel
- .updateLimitedBy(fieldValues, model, operator, returnModel, limit) ⇒
Array.<PGActiveModel>
- .updateAllBy(fieldValues, model, operator, returnModel) ⇒
Array.<PGActiveModel>
- .updateAll(model) ⇒
Array.<PGActiveModel>
- .create(model) ⇒
pgActiveModel.addProperty(name, value)
Adds a property to this model that does not affect it from a database perspective.
Kind: instance method of PGActiveModel
Param | Type | Description |
---|---|---|
name | String | The name of the property. |
value | Any | The the value to set the property. |
pgActiveModel.find() ⇒ PGActiveModel
Retrieves the current model by its set field with type PGTypes.PK
Kind: instance method of PGActiveModel
Returns: PGActiveModel
- Returns it's self.
pgActiveModel.delete() ⇒ PGActiveModel
Deletes the current model by its set field with type PGTypes.PK
Kind: instance method of PGActiveModel
Returns: PGActiveModel
- Returns it's self.
pgActiveModel.create() ⇒ PGActiveModel
Creates a new row with the currently set properties.
Kind: instance method of PGActiveModel
Returns: PGActiveModel
- Returns it's self.
pgActiveModel.save() ⇒ PGActiveModel
Saves the model with its changed properties.
Kind: instance method of PGActiveModel
Returns: PGActiveModel
- Returns it's self.
pgActiveModel.update() ⇒ PGActiveModel
Updates the model with the passed in changed properties.
Kind: instance method of PGActiveModel
Returns: PGActiveModel
- Returns it's self.
pgActiveModel.decrypt(…props) ⇒ PGActiveModel
Decrypts the properties on the model based on which stringed names are passed in as arguments.
Kind: instance method of PGActiveModel
Returns: PGActiveModel
- Returns it's self.
Param | Type | Description |
---|---|---|
…props | String | name of each property. |
pgActiveModel.encrypt(…props) ⇒ PGActiveModel
Encrypts the properties on the model based on which stringed names are passed in as arguments.
Kind: instance method of PGActiveModel
Returns: PGActiveModel
- Returns it's self.
Param | Type | Description |
---|---|---|
…props | String | name of each property. |
pgActiveModel.redactSensitiveData(redactionCensor) ⇒ PGActiveModel
Redacts all encrypted fields from the model.
Kind: instance method of PGActiveModel
Returns: PGActiveModel
- Returns it's self.
Param | Type | Default | Description |
---|---|---|---|
redactionCensor | String | "[redacted]" | The string to replace the encrypted values with. |
pgActiveModel.getEncryptedProfile() ⇒ String
Gets the encrypted profile that the model has set.
Kind: instance method of PGActiveModel
Returns: String
- Returns it's self.
PGActiveModel.create(model) ⇒ PGActiveModel
Creates a new row with the passed in props and values.
Kind: static method of PGActiveModel
Returns: PGActiveModel
- Returns it's self.
Param | Type | Description |
---|---|---|
model | Object | A plain object with the name of the properties and their values to be set with the new model. |
Example
create({
username: 'foo',
email: 'test@test.com',
});
PGActiveModel.findById(id) ⇒ PGActiveModel
Retrives a model by it's PK.
Kind: static method of PGActiveModel
Returns: PGActiveModel
- Returns a new model.
Param | Type | Description |
---|---|---|
id | String | The PK of the model to retrieve. |
PGActiveModel.findLimtedBy(fieldValues, operator, limit) ⇒ Array.<PGActiveModel>
Retrives a limited amount models by the passed in fieldValues
.
Kind: static method of PGActiveModel
Returns: Array.<PGActiveModel>
- Returns an array of new models.
Param | Type | Default | Description |
---|---|---|---|
fieldValues | Object | A plain object with the properties and their values to retrive by. | |
operator | String | AND | The query operator to use between each of the fieldValues [AND , OR , 'NOT'] |
limit | Number | The limit to stop searching when the records retrived are equal or greater than the set limit . |
Example
findLimtedBy({
username: ['user2', 'OR', 'user3'],
email: null,
}, 'AND', 5);
PGActiveModel.findAllBy(fieldValues, operator) ⇒ Array.<PGActiveModel>
Retrives all models by the passed in fieldValues. Will stop searching when the records retrived are equal or greater than limit
.
Kind: static method of PGActiveModel
Returns: Array.<PGActiveModel>
- Returns an array of new models.
Param | Type | Default | Description |
---|---|---|---|
fieldValues | Object | A plain object with the properties and their values to retrive by. | |
operator | String | AND | The query operator to use between each of the fieldValues [AND , OR , 'NOT'] |
Example
findAllBy({
username: ['user2', 'OR', 'user3'],
email: null,
}, 'AND');
PGActiveModel.findAll() ⇒ Array.<PGActiveModel>
Retrives all rows in the table of the model.
Kind: static method of PGActiveModel
Returns: Array.<PGActiveModel>
- Returns an array of new models.
PGActiveModel.deleteById(id) ⇒ PGActiveModel
Deletes a model that is found by it's PK with the passed in props and values.
Kind: static method of PGActiveModel
Returns: PGActiveModel
- Returns a new model or null
Param | Type | Description |
---|---|---|
id | String | The PK of the model to delete. |
PGActiveModel.deleteLimitedBy(fieldValues, operator, limit) ⇒ Array.<PGActiveModel>
Deletes a limited amount models by the passed in fieldValues.
Kind: static method of PGActiveModel
Returns: Array.<PGActiveModel>
- Returns an array of deleted models.
Param | Type | Default | Description |
---|---|---|---|
fieldValues | Object | A plain object with the properties and their values to delete by. | |
operator | String | AND | The query operator to use between each of the fieldValues [AND , OR , 'NOT'] |
limit | Number | The limit to stop deleting when the records retrived are equal or greater than the set limit . |
Example
deleteLimitedBy({
registered: false,
},'AND', 5);
PGActiveModel.deleteAllBy(fieldValues, operator) ⇒ Array.<PGActiveModel>
Deletes all models by the passed in fieldValues
.
Kind: static method of PGActiveModel
Returns: Array.<PGActiveModel>
- Returns an array of deleted models.
Param | Type | Default | Description |
---|---|---|---|
fieldValues | Object | A plain object with the properties and their values to delete by. | |
operator | String | AND | The query operator to use between each of the fieldValues [AND , OR , 'NOT'] |
Example
deleteAllBy({
registered: true,
});
PGActiveModel.deleteAll() ⇒ Array.<PGActiveModel>
Deletes all models in their table.
Kind: static method of PGActiveModel
Returns: Array.<PGActiveModel>
- Returns an array of deleted models or null
PGActiveModel.updateById(id, model, returnModel) ⇒ PGActiveModel
Updates a model that is found by it's PK with the passed in props and values.
Kind: static method of PGActiveModel
Returns: PGActiveModel
- Returns a new model or null
Param | Type | Default | Description |
---|---|---|---|
id | String | The PK of the model to update. | |
model | Object | A plain object with the name of the properties and their values to update the model with. | |
returnModel | Boolean | true | If the updated model should be returned or not. It will return null if this is set to false. |
Example
updateById('09A75A84-A921-4F68-8FEF-B8392E3702C2',
{
password: 'bestpasswordinalltheland12346969420'
});
PGActiveModel.updateLimitedBy(fieldValues, model, operator, returnModel, limit) ⇒ Array.<PGActiveModel>
Updates models that are found by the passed in fieldValues
with the passed in props and values of the model
.
Kind: static method of PGActiveModel
Returns: Array.<PGActiveModel>
- Returns an array of updated models or null
Param | Type | Default | Description |
---|---|---|---|
fieldValues | Object | A plain object with the properties and their values to update by. | |
model | Object | A plain object with the name of the properties and their values to update the model with. | |
operator | String | AND | The query operator to use between each of the fieldValues [AND , OR , 'NOT'] |
returnModel | Boolean | true | If the updated model should be returned or not. It will return null if this is set to false. |
limit | Number | The limit to stop searching when the records retrived are equal or greater than the set limit . |
Example
updateLimitedBy({
password: null
},
{
password: 'bestpasswordinalltheland12346969420'
},'AND', true, 5);
PGActiveModel.updateAllBy(fieldValues, model, operator, returnModel) ⇒ Array.<PGActiveModel>
Updates all models that are found by the passed in fieldValues
with the passed in props and values of the model
.
Kind: static method of PGActiveModel
Returns: Array.<PGActiveModel>
- Returns an array of updated models or null
Param | Type | Default | Description |
---|---|---|---|
fieldValues | Object | A plain object with the properties and their values to update by. | |
model | Object | A plain object with the name of the properties and their values to update the model with. | |
operator | String | AND | The query operator to use between each of the fieldValues [AND , OR , 'NOT'] |
returnModel | Boolean | true | If the updated model should be returned or not. It will return null if this is set to false. |
Example
updateAllBy({
password: null
},
{
password: 'bestpasswordinalltheland12346969420'
});
PGActiveModel.updateAll(model) ⇒ Array.<PGActiveModel>
Updates all models in their table with the passed in props and values of the model
.
Kind: static method of PGActiveModel
Returns: Array.<PGActiveModel>
- Returns an array of updated models or null
Param | Type | Description |
---|---|---|
model | Object | A plain object with the name of the properties and their values to update the models with. |
Example
updateAll({
password: 'bestpasswordinalltheland12346969420'
});
PGBaseModel
Postgres Base Model class to extend a custom model from.
PGConnecter
Postgres Connecter to initialize the singleton for connection.
new PGConnecter(options)
Param | Type | Default | Description |
---|---|---|---|
options | Object | The connection options. | |
options.crypto | Crypto | postgres/crypto/interface.js | The implemented crypto interface that follows postgres/crypto/interface.js |
options.pg | Object | The options object to pass into pg lib. | |
options.pg.user | String | process.env.PGUSER | User's name. |
options.pg.password | String | process.env.PGPASSWORD | User's password. |
options.pg.database | String | process.env.PGDATABASE | Database's name. |
options.pg.port | Number | process.env.PGPORT | Database's port. |
options.pg.connectionString | String | Postgres formated connection string. e.g. postgres://user:password@host:5432/database | |
options.pg.ssl | TLSSocket | Options to be passed into the native Node.js TLSSocket socket. | |
options.pg.types | pg.types | Custom type parsers. See node-postgres types for more details. | |
options.pg.statement_timeout | Number | 0 | Number of milliseconds before a statement in query will time out. |
options.pg.query_timeout | Number | 0 | number of milliseconds before a query call will timeout. |
options.pg.connectionTimeoutMillis | Number | 0 | Number of milliseconds to wait before timing out when connecting a new client. |
options.pg.idleTimeoutMillis | Number | 10000 | Number of milliseconds a client must sit idle in the pool and not be checked out before it is disconnected from the backend and discarded. |
options.pg.max | Number | 10 | Maximum number of clients the pool should contain. |
Example
var pgOptions = {
pg: {
connectionString: 'postgres://postgres@localhost/pgtest',
}
};
try {
pgOptions.crypto = require('@abeai/node-crypto').utils.pgCrypto;
} catch (_) {
console.log(_);
}
var pg = new PGConnecter(pgOptions);
PGEncryptModel ⇐ PGBaseModel
Postgres Encryption Model class to extend a custom model from.
Kind: global class
Extends: PGBaseModel
PGTypes
The types of fields for Postgres Models.
Kind: global constant
PGTypes.PK
The primary key of the table.
Kind: static property of PGTypes
PGTypes.Encrypt
Marks this field to auto encrypt/hash (for look up) but not auto decrypt it on retrieval. The table will need to have a field with the same name as this set field with __
as a prefix.
Kind: static property of PGTypes
Example
//if you have an encrypted field called `phone` the sql query for creating the table may look like this
CREATE TABLE IF NOT EXISTS users (
phone VARCHAR (500),
__phone VARCHAR (500) UNIQUE,
);
PGTypes.EncryptWithoutHash
Marks this field to auto encrypt but not auto decrypt it on retrieval. Same as Encrypt
but with no lookup hash.
Kind: static property of PGTypes
PGTypes.EncryptProfile
Marks this field as the encryption profile for encrypting/decrypting/hashing utilizing aws kms.
Kind: static property of PGTypes
PGTypes.AutoCrypt
Marks this field to auto encrypt/hash (for look up) and to auto decrypt it on retrieval.
Kind: static property of PGTypes
PGTypes.AutoCryptWithoutHash
Marks this field to auto encrypt and auto decrypt it on retrieval. Same as AutoCrypt
but with no lookup hash.
Kind: static property of PGTypes
PGTypes.Hash
Marks this field to be hashed on creation (IE: Password and other information you want to protect)
Kind: static property of PGTypes
camelCase(str) ⇒ String
Converts string
to camel case.
Kind: global function
Returns: String
- Returns the camel cased string.
Param | Type | Default | Description |
---|---|---|---|
str | String | '' | The string to convert. |
Example
camelCase('Foo Bar');
// => 'fooBar'
camelCase('--foo-bar--');
// => 'fooBar'
camelCase('__FOO_BAR__');
// => 'fooBar'
cloneDeep(value) ⇒ \*
This method is like clone
except that it recursively clones value
.
Kind: global function
Returns: \*
- Returns the deep cloned value.
Param | Type | Description |
---|---|---|
value | \* | The value to recursively clone. |
Example
var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false
cloneDeepWith(value, [cb]) ⇒ \*
This method is like cloneWith
except that it recursively clones value
.
Kind: global function
Returns: \*
- Returns the deep cloned value.
Param | Type | Description |
---|---|---|
value | \* | The value to recursively clone. |
[cb] | function | The function to customize cloning. |
Example
function customizer(value) {
if (_.isElement(value)) {
return value.cloneNode(true);
}
}
var el = cloneDeepWith(document.body, customizer);
console.log(el === document.body);
// => false
console.log(el.nodeName);
// => 'BODY'
console.log(el.childNodes.length);
// => 20
merge(object, […sources]) ⇒ Object
This method is like assign
except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined
are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.
Note: This method mutates object
.
Kind: global function
Returns: Object
- Returns object
.
Param | Type | Description |
---|---|---|
object | Object | The destination object. |
[…sources] | Object | The source objects. |
Example
var object = {
'a': [{ 'b': 2 }, { 'd': 4 }]
};
var other = {
'a': [{ 'c': 3 }, { 'e': 5 }]
};
merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
debounce(func, delay) ⇒ function
Creates a debounced function that delays invoking func
until after wait
milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with a cancel
method to cancel delayed func
invocations and a flush
method to immediately invoke them. Provide options
to indicate whether func
should be invoked on the leading and/or trailing edge of the wait
timeout. The func
is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last func
invocation.
Note: If leading
and trailing
options are true
, func
is invoked on the trailing edge of the timeout only if the debounced function is invoked more than once during the wait
timeout.
If wait
is 0
and leading
is false
, func
invocation is deferred until to the next tick, similar to setTimeout
with a timeout of 0
.
See David Corbacho's article for details over the differences between _.debounce
and _.throttle
.
Kind: global function
Returns: function
- Returns the new debounced function.
Param | Type | Default | Description |
---|---|---|---|
func | function | The function to debounce. | |
delay | Number | 0 | The number of milliseconds to delay. |
Example
// Avoid costly calculations while the window size is in flux.
jQuery(window).on('resize', debounce(calculateLayout, 150));
// Invoke `sendMail` when clicked, debouncing subsequent calls.
jQuery(element).on('click', debounce(sendMail, 300, {
'leading': true,
'trailing': false
}));
// Ensure `batchLog` is invoked once after 1 second of debounced calls.
var debounced = debounce(batchLog, 250, { 'maxWait': 1000 });
var source = new EventSource('/stream');
jQuery(source).on('message', debounced);
// Cancel the trailing debounced invocation.
jQuery(window).on('popstate', debounced.cancel);
forEach(collection, cb) ⇒ Array
| Object
Iterates over elements of collection
and invokes iteratee
for each element. The iteratee is invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false
.
Kind: global function
Returns: Array
| Object
- Returns collection
.
Param | Type | Description |
---|---|---|
collection | Array | Object | The collection to iterate over. |
cb | function | The function invoked per iteration. |
Example
forEach([1, 2], function(value) {
console.log(value);
});
// => Logs `1` then `2`.
forEach({ 'a': 1, 'b': 2 }, function(value, key) {
console.log(key);
});
// => Logs 'a' then 'b' (iteration order is not guaranteed).
get(object, path, [defaultReturn]) ⇒ \*
Gets the value at path
of object
. If the resolved value is undefined
, the defaultValue
is returned in its place.
Kind: global function
Returns: \*
- Returns the resolved value.
Param | Type | Description |
---|---|---|
object | Object | The object to query. |
path | Array | The path of the property to get. |
[defaultReturn] | \* | The value returned for undefined resolved values. |
Example
var object = { 'a': [{ 'b': { 'c': 3 } }] };
get(object, 'a[0].b.c');
// => 3
get(object, ['a', '0', 'b', 'c']);
// => 3
isEmpty(value) ⇒ boolean
Checks if value
is an empty object or array
Objects are considered empty if they have no own enumerable string keyed properties.
Kind: global function
Returns: boolean
- Returns true
if value
is empty, else false
.
Param | Type | Description |
---|---|---|
value | \* | The value to check. |
Example
isEmpty({});
// => true
isEmpty([]);
// => true
isEmpty([1, 2, 3]);
// => false
isEmpty({ 'a': 1 });
// => false
isObject(value) ⇒ boolean
Checks if value
is the language type of Object
. (e.g. arrays, functions, objects, regexes, new Number(0)
, and new String('')
)
Kind: global function
Returns: boolean
- Returns true
if value
is an object, else false
.
Param | Type | Description |
---|---|---|
value | \* | The value to check. |
Example
isObject({});
// => true
isObject([1, 2, 3]);
// => true
isObject(null);
// => false
kebabCase(str) ⇒ String
Converts string
to kebab case.
Kind: global function
Returns: String
- Returns the kebab cased string.
Param | Type | Default | Description |
---|---|---|---|
str | String | '' | The string to convert. |
Example
kebabCase('Foo Bar');
// => 'foo-bar'
kebabCase('fooBar');
// => 'foo-bar'
kebabCase('__FOO_BAR__');
// => 'foo-bar'
keysToCamel(o) ⇒ String
Converts Object's keys from snake,kebab and space case to camel case.
Kind: global function
Returns: String
- Returns the object with it's key's camelcased.
Param | Type | Description |
---|---|---|
o | Object | The object to convert. |
Example
keysToCamel({foo_bar:{bar_meme:20}})
// => {fooBar:{barMeme:20}}
mapKeys(object, iteratee) ⇒ Object
This method creates an object with the same values as object
and keys generated by running each own enumerable string keyed property of object
thru iteratee
. The iteratee is invoked with two arguments: (value, key).
Kind: global function
Returns: Object
- Returns the new mapped object.
Param | Type | Description |
---|---|---|
object | Object | The object to iterate over. |
iteratee | function | The function invoked per iteration. |
Example
mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
return key + value;
});
// => { 'a1': 1, 'b2': 2 }
request(options) ⇒ Promise
Makes a HTTP/S Request to a given url.
Kind: global function
Returns: Promise
- Returns the promise that gets resolved or rejected.
Param | Type | Default | Description |
---|---|---|---|
options | Object | Supports all of nodes HTTP/S Module's options + the folloing. | |
options.uri | String | fully qualified uri. | |
options.method | String | GET | http method. |
options.headers | Object | {} | http headers. |
options.qs | Object | object containing querystring values to be appended to the uri . | |
options.simple | Boolean | true | throws an error for any non 2xx status code response. |
options.resolveWithFullResponse | Boolean | false | set to true if the full response object is wanted instead of just the body data. |
options.qs | Object | object containing querystring values to be appended to the uri . | |
options.body | Object | Buffer | String | ReadSteam | entity body for PATCH, POST and PUT requests. Must be a Buffer , String or ReadStream . If json is true, then body must be a JSON-serializable object. | |
options.form | Object | when passed an object or a querystring, this sets body to a querystring representation of value, and adds Content-type: application/x-www-form-urlencoded header . | |
options.json | Boolean | setsbody to JSON representation of value and adds Content-type: application/json header . Additionally, parses the response body as JSON. | |
options.keepAlive | Boolean | true | set to false to turn off keepAlive sockets. |
options.authorization.basic | Object | takes an object with client and secret props to create a Authorization: Basic client:secret base64 header. | |
options.authorization.bearer | String | creates a Authorization: Bearer bearer header. | |
options.redirectMax | Number | 5 | number of times the request will follow a redirect from the server. |
options.logger | Object | the pino logger to log errors. |
Example
await request({
uri: 'http://127.0.0.1:4261/'),
simple: false,
resolveWithFullResponse: true
});
set(object, path, value) ⇒ Object
Sets the value at path
of object
. If a portion of path
doesn't exist, it's created. Arrays are created for missing index properties while objects are created for all other missing properties.
Note: This method mutates object
.
Kind: global function
Returns: Object
- Returns object
.
Param | Type | Description |
---|---|---|
object | Object | The object to modify. |
path | Array | The path of the property to set. |
value | \* | The value to set. |
Example
var object = { 'a': [{ 'b': { 'c': 3 } }] };
set(object, ['x', '0', 'y', 'z'], 5);
console.log(object.x[0].y.z);
// => 5
snakeCase(str) ⇒ String
Converts string
to snake case.
Kind: global function
Returns: String
- Returns the snake cased string.
Param | Type | Default | Description |
---|---|---|---|
str | String | '' | The string to convert. |
Example
snakeCase('Foo Bar');
// => 'foo_bar'
snakeCase('fooBar');
// => 'foo_bar'
snakeCase('--FOO-BAR--');
// => 'foo_bar'
toPath(value) ⇒ Array
Converts value
to a property path array.
Kind: global function
Returns: Array
- Returns the new property path array.
Param | Type | Description |
---|---|---|
value | String | The value to convert. |
Example
toPath('a.b.c');
// => ['a', 'b', 'c']
toPath('a[0].b.c');
// => ['a', '0', 'b', 'c']