@abeai/node-utils 中文文档教程

发布于 4年前 浏览 33 项目主页 更新于 3年前

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

计时器类,用于保持准确的秒表时间。

PGActiveModelPGEncryptModel

从中扩展自定义模型的 Postgres 活动模型类。

PGBaseModel

从中扩展自定义模型的 Postgres 基本模型类。

PGConnecter

Postgres Connecter 初始化单例连接。

PGEncryptModelPGBaseModel

从中扩展自定义模型的 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 的结果 调用。

注意:如果leadingtrailing选项是truefunc是 仅当去抖函数时在超时的后沿调用 在 wait 超时期间被多次调用。

如果 wait0leadingfalse,则延迟 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])*

获取 objectpath 处的值。 如果解析值是 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 相同的值和通过运行每个自己的可枚举生成的键 objectiteratee 的字符串键控属性。 迭代器被调用 有两个参数:(值,键)。

request(options)Promise

向给定的 url 发出 HTTP/S 请求。

set(object, path, value)Object

objectpath 处设置值。 如果 path 的一部分不存在, 它被创建了。 数组是为缺失的索引属性创建的,而对象 为所有其他缺失的属性创建。

注意:此方法会改变对象

snakeCase(str)String

string 转换为 蛇案

toPath(value)Array

value 转换为属性路径数组。

Timer

计时器类,用于保持准确的秒表时间。

Kind:全局类

new Timer(startTime, totalTime)

构造一个 Timer 实例。

返回Timer - 返回新的 Timer 实例。

ParamTypeDefaultDescription
startTimeBigInt0the time the Timer started at.
totalTimeBigInt0the total time the Timer elapsed.

timer.start() ⇒ Timer

启动秒表

KindTimer 的实例方法
返回Timer - 返回它自己。

timer.stop() ⇒ Timer

停止秒表

KindTimer 的实例方法
返回Timer - 返回它自己。

timer.ns() ⇒ Number

获取经过的时间(以纳秒为单位)。

KindTimer
的实例方法 返回Number - ns.

timer.us() ⇒ Number

获取经过的时间(以微秒为单位)。

KindTimer
的实例方法 退货编号 - 我们。

timer.ms() ⇒ Number

获取经过的时间(以毫秒为单位)。

KindTimer
的实例方法 退货编号 - 女士。

PGActiveModel ⇐ PGEncryptModel

从中扩展自定义模型的 Postgres 活动模型类。

种类:全局类
扩展PGEncryptModel

pgActiveModel.addProperty(name, value)

向该模型添加一个属性从数据库的角度来看,这不会影响它。

KindPGActiveModel的实例方法

ParamTypeDescription
nameStringThe name of the property.
valueAnyThe the value to set the property.

pgActiveModel.find() ⇒ PGActiveModel

检索当前通过其设置字段类型为 PGTypes.PK 的模型

KindPGActiveModel 的实例方法
返回PGActiveModel - 返回它自己。

pgActiveModel.delete() ⇒ PGActiveModel

通过PGTypes.PK 类型的集合字段删除当前模型

Kind: PGActiveModel
返回PGActiveModel - 返回它自己。

pgActiveModel.create() ⇒ PGActiveModel

使用当前设置的属性创建一个新行。

KindPGActiveModel
的实例方法 返回PGActiveModel - 返回它自己。

pgActiveModel.save() ⇒ PGActiveModel

保存模型及其更改的属性。

KindPGActiveModel
的实例方法 返回PGActiveModel - 返回它自己。

pgActiveModel.update() ⇒ PGActiveModel

使用传入的更改属性更新模型。

KindPGActiveModel
的实例方法 返回PGActiveModel - 返回它自己。

pgActiveModel.decrypt(…props) ⇒ PGActiveModel

根据将字符串名称作为参数传入模型来解密模型的属性。

KindPGActiveModel
的实例方法 返回PGActiveModel - 返回它自己。

ParamTypeDescription
…propsStringname of each property.

pgActiveModel.encrypt(…props) ⇒ PGActiveModel

根据将字符串名称作为参数传入的模型属性加密。

KindPGActiveModel
的实例方法 返回PGActiveModel - 返回它自己。

ParamTypeDescription
…propsStringname of each property.

pgActiveModel.redactSensitiveData(redactionCensor) ⇒ PGActiveModel

编辑模型中的所有加密字段。

KindPGActiveModel
的实例方法 返回PGActiveModel - 返回它自己。

ParamTypeDefaultDescription
redactionCensorString"[redacted]"The string to replace the encrypted values with.

pgActiveModel.getEncryptedProfile() ⇒ String

获取模型设置的加密配置文件。

KindPGActiveModel
的实例方法 返回String - 返回它本身。

PGActiveModel.create(model) ⇒ PGActiveModel

使用传入的属性和值创建一个新行。

种类PGActiveModel
的静态方法 返回PGActiveModel - 返回它自己。

ParamTypeDescription
modelObjectA 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 - 返回一个新模型。

ParamTypeDescription
idStringThe PK of the model to retrieve.

PGActiveModel.findLimtedBy(fieldValues, operator, limit) ⇒ Array.<PGActiveModel>

通过传入的 fieldValues 检索有限数量的模型。

种类PGActiveModel
的静态方法 返回Array.<PGActiveModel> - 返回一组新模型。

ParamTypeDefaultDescription
fieldValuesObjectA plain object with the properties and their values to retrive by.
operatorStringANDThe query operator to use between each of the fieldValues [AND, OR, 'NOT']
limitNumberThe 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> - 返回一组新模型。

ParamTypeDefaultDescription
fieldValuesObjectA plain object with the properties and their values to retrive by.
operatorStringANDThe 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

ParamTypeDescription
idStringThe PK of the model to delete.

PGActiveModel.deleteLimitedBy(fieldValues, operator, limit) ⇒ Array.<PGActiveModel>

通过传入的 fieldValues 删除有限数量的模型。

种类PGActiveModel
的静态方法 返回Array.<PGActiveModel> - 返回已删除模型的数组。

ParamTypeDefaultDescription
fieldValuesObjectA plain object with the properties and their values to delete by.
operatorStringANDThe query operator to use between each of the fieldValues [AND, OR, 'NOT']
limitNumberThe 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> - 返回已删除模型的数组。

ParamTypeDefaultDescription
fieldValuesObjectA plain object with the properties and their values to delete by.
operatorStringANDThe 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 - 返回新模型或空

ParamTypeDefaultDescription
idStringThe PK of the model to update.
modelObjectA plain object with the name of the properties and their values to update the model with.
returnModelBooleantrueIf 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

ParamTypeDefaultDescription
fieldValuesObjectA plain object with the properties and their values to update by.
modelObjectA plain object with the name of the properties and their values to update the model with.
operatorStringANDThe query operator to use between each of the fieldValues [AND, OR, 'NOT']
returnModelBooleantrueIf the updated model should be returned or not. It will return null if this is set to false.
limitNumberThe 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

ParamTypeDefaultDescription
fieldValuesObjectA plain object with the properties and their values to update by.
modelObjectA plain object with the name of the properties and their values to update the model with.
operatorStringANDThe query operator to use between each of the fieldValues [AND, OR, 'NOT']
returnModelBooleantrueIf 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

ParamTypeDescription
modelObjectA 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)

ParamTypeDefaultDescription
optionsObjectThe connection options.
options.cryptoCryptopostgres/crypto/interface.jsThe implemented crypto interface that follows postgres/crypto/interface.js
options.pgObjectThe options object to pass into pg lib.
options.pg.userStringprocess.env.PGUSERUser's name.
options.pg.passwordStringprocess.env.PGPASSWORDUser's password.
options.pg.databaseStringprocess.env.PGDATABASEDatabase's name.
options.pg.portNumberprocess.env.PGPORTDatabase's port.
options.pg.connectionStringStringPostgres formated connection string. e.g. postgres://user:password@host:5432/database
options.pg.sslTLSSocketOptions to be passed into the native Node.js TLSSocket socket.
options.pg.typespg.typesCustom type parsers. See node-postgres types for more details.
options.pg.statement_timeoutNumber0Number of milliseconds before a statement in query will time out.
options.pg.query_timeoutNumber0number of milliseconds before a query call will timeout.
options.pg.connectionTimeoutMillisNumber0Number of milliseconds to wait before timing out when connecting a new client.
options.pg.idleTimeoutMillisNumber10000Number 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.maxNumber10Maximum 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

将此字段标记为在创建时进行哈希处理(即:密码和您要保护的其他信息)

KindPGTypes

camelCase(str) ⇒ String

string 转换为 驼峰式大小写

种类:全局函数
返回String - 返回驼峰式字符串。

ParamTypeDefaultDescription
strString''The string to convert.

示例

camelCase('Foo Bar');
// => 'fooBar'

camelCase('--foo-bar--');
// => 'fooBar'

camelCase('__FOO_BAR__');
// => 'fooBar'

cloneDeep(value) ⇒ \*

此方法类似于clone,只是它递归地克隆value

种类:全局函数
返回\* - 返回深度克隆值。

ParamTypeDescription
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

种类:全局函数
返回\* - 返回深度克隆值。

ParamTypeDescription
value\*The value to recursively clone.
[cb]functionThe 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 的源属性是 如果目标值存在则跳过。 数组和普通对象属性 被递归合并。 其他对象和值类型被覆盖 任务。 源对象从左到右应用。 随后的 来源覆盖以前来源的属性分配。

注意:此方法会改变对象

种类:全局函数
返回对象 - 返回对象

ParamTypeDescription
objectObjectThe destination object.
[…sources]ObjectThe 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 的结果 调用。

注意:如果leadingtrailing选项是truefunc是 仅当去抖函数时在超时的后沿调用 在 wait 超时期间被多次调用。

如果 wait0leadingfalse,则延迟 func 调用 直到下一个滴答声,类似于 setTimeout,超时为 0

请参阅 David Corbacho 的文章 有关 _.debounce_.throttle 之间差异的详细信息。

种类:全局函数
返回function - 返回新的去抖函数。

ParamTypeDefaultDescription
funcfunctionThe function to debounce.
delayNumber0The 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 提前退出迭代。

种类:全局函数
返回数组 | 对象 - 返回集合

ParamTypeDescription
collectionArray | ObjectThe collection to iterate over.
cbfunctionThe 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]) ⇒ \*

获取objectpath 处的值。 如果解析值是 undefined,返回 defaultValue

种类:全局函数
返回\* - 返回解析后的值。

ParamTypeDescription
objectObjectThe object to query.
pathArrayThe 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

ParamTypeDescription
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

ParamTypeDescription
value\*The value to check.

示例

isObject({});
// => true

isObject([1, 2, 3]);
// => true


isObject(null);
// => false

kebabCase(str) ⇒ String

string 转换为 烤肉串

种类:全局函数
返回String - 返回 kebab 大小写的字符串。

ParamTypeDefaultDescription
strString&#x27;&#x27;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 - 返回带有驼峰式键的对象。

ParamTypeDescription
oObjectThe object to convert.

示例

keysToCamel({foo_bar:{bar_meme:20}})
// => {fooBar:{barMeme:20}}

mapKeys(object, iteratee) ⇒ Object

这个方法创建了一个对象 与 object 相同的值和通过运行每个自己的可枚举生成的键 objectiteratee 的字符串键控属性。 迭代器被调用 有两个参数:(值,键)。

种类:全局函数
返回对象 - 返回新的映射对象。

ParamTypeDescription
objectObjectThe object to iterate over.
iterateefunctionThe 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 - 返回已解决或被拒绝的承诺。

ParamTypeDefaultDescription
optionsObjectSupports all of nodes HTTP/S Module's options + the folloing.
options.uriStringfully qualified uri.
options.methodStringGEThttp method.
options.headersObject{}http headers.
options.qsObjectobject containing querystring values to be appended to the uri.
options.simpleBooleantruethrows an error for any non 2xx status code response.
options.resolveWithFullResponseBooleanfalseset to true if the full response object is wanted instead of just the body data.
options.qsObjectobject containing querystring values to be appended to the uri.
options.bodyObject | Buffer | String | ReadSteamentity 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.formObjectwhen 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.jsonBooleansetsbody to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON.
options.keepAliveBooleantrueset to false to turn off keepAlive sockets.
options.authorization.basicObjecttakes an object with client and secret props to create a Authorization: Basic client:secret base64 header.
options.authorization.bearerStringcreates a Authorization: Bearer bearer header.
options.redirectMaxNumber5number of times the request will follow a redirect from the server.
options.loggerObjectthe pino logger to log errors.

示例

await request({
       uri: 'http://127.0.0.1:4261/'),
       simple: false,
       resolveWithFullResponse: true
   });

set(object, path, value) ⇒ Object

objectpath 处设置值。 如果 path 的一部分不存在, 它被创建了。 数组是为缺失的索引属性创建的,而对象 为所有其他缺失的属性创建。

注意:此方法会改变对象

种类:全局函数
返回对象 - 返回对象

ParamTypeDescription
objectObjectThe object to modify.
pathArrayThe 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 - 返回蛇形字符串。

ParamTypeDefaultDescription
strString&#x27;&#x27;The string to convert.

示例

snakeCase('Foo Bar');
// => 'foo_bar'

snakeCase('fooBar');
// => 'foo_bar'

snakeCase('--FOO-BAR--');
// => 'foo_bar'

toPath(value) ⇒ Array

value 转换为属性路径数组。

种类:全局函数
返回Array - 返回新的属性路径数组。

ParamTypeDescription
valueStringThe 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.

PGActiveModelPGEncryptModel

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.

PGEncryptModelPGBaseModel

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 clones value.

cloneDeepWith(value, [cb])*

This method is like cloneWith except that it recursively clones value.

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.

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.

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.

get(object, path, [defaultReturn])*

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.

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.

isObject(value)boolean

Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), and new 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 of object thru iteratee. 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 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.

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.

ParamTypeDefaultDescription
startTimeBigInt0the time the Timer started at.
totalTimeBigInt0the 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.addProperty(name, value)

Adds a property to this model that does not affect it from a database perspective.

Kind: instance method of PGActiveModel

ParamTypeDescription
nameStringThe name of the property.
valueAnyThe 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.

ParamTypeDescription
…propsStringname 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.

ParamTypeDescription
…propsStringname 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.

ParamTypeDefaultDescription
redactionCensorString&quot;[redacted]&quot;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.

ParamTypeDescription
modelObjectA 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.

ParamTypeDescription
idStringThe PK of the model to retrieve.

PGActiveModel.findLimtedBy(fieldValues, operator, limit) ⇒ Array.&lt;PGActiveModel&gt;

Retrives a limited amount models by the passed in fieldValues.

Kind: static method of PGActiveModel
Returns: Array.&lt;PGActiveModel&gt; - Returns an array of new models.

ParamTypeDefaultDescription
fieldValuesObjectA plain object with the properties and their values to retrive by.
operatorStringANDThe query operator to use between each of the fieldValues [AND, OR, 'NOT']
limitNumberThe 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.&lt;PGActiveModel&gt;

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.&lt;PGActiveModel&gt; - Returns an array of new models.

ParamTypeDefaultDescription
fieldValuesObjectA plain object with the properties and their values to retrive by.
operatorStringANDThe query operator to use between each of the fieldValues [AND, OR, 'NOT']

Example

findAllBy({
      username: ['user2', 'OR', 'user3'],
      email: null,
   }, 'AND');

PGActiveModel.findAll() ⇒ Array.&lt;PGActiveModel&gt;

Retrives all rows in the table of the model.

Kind: static method of PGActiveModel
Returns: Array.&lt;PGActiveModel&gt; - 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

ParamTypeDescription
idStringThe PK of the model to delete.

PGActiveModel.deleteLimitedBy(fieldValues, operator, limit) ⇒ Array.&lt;PGActiveModel&gt;

Deletes a limited amount models by the passed in fieldValues.

Kind: static method of PGActiveModel
Returns: Array.&lt;PGActiveModel&gt; - Returns an array of deleted models.

ParamTypeDefaultDescription
fieldValuesObjectA plain object with the properties and their values to delete by.
operatorStringANDThe query operator to use between each of the fieldValues [AND, OR, 'NOT']
limitNumberThe 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.&lt;PGActiveModel&gt;

Deletes all models by the passed in fieldValues.

Kind: static method of PGActiveModel
Returns: Array.&lt;PGActiveModel&gt; - Returns an array of deleted models.

ParamTypeDefaultDescription
fieldValuesObjectA plain object with the properties and their values to delete by.
operatorStringANDThe query operator to use between each of the fieldValues [AND, OR, 'NOT']

Example

deleteAllBy({
      registered: true,
   });

PGActiveModel.deleteAll() ⇒ Array.&lt;PGActiveModel&gt;

Deletes all models in their table.

Kind: static method of PGActiveModel
Returns: Array.&lt;PGActiveModel&gt; - 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

ParamTypeDefaultDescription
idStringThe PK of the model to update.
modelObjectA plain object with the name of the properties and their values to update the model with.
returnModelBooleantrueIf 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.&lt;PGActiveModel&gt;

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.&lt;PGActiveModel&gt; - Returns an array of updated models or null

ParamTypeDefaultDescription
fieldValuesObjectA plain object with the properties and their values to update by.
modelObjectA plain object with the name of the properties and their values to update the model with.
operatorStringANDThe query operator to use between each of the fieldValues [AND, OR, 'NOT']
returnModelBooleantrueIf the updated model should be returned or not. It will return null if this is set to false.
limitNumberThe 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.&lt;PGActiveModel&gt;

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.&lt;PGActiveModel&gt; - Returns an array of updated models or null

ParamTypeDefaultDescription
fieldValuesObjectA plain object with the properties and their values to update by.
modelObjectA plain object with the name of the properties and their values to update the model with.
operatorStringANDThe query operator to use between each of the fieldValues [AND, OR, 'NOT']
returnModelBooleantrueIf 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.&lt;PGActiveModel&gt;

Updates all models in their table with the passed in props and values of the model.

Kind: static method of PGActiveModel
Returns: Array.&lt;PGActiveModel&gt; - Returns an array of updated models or null

ParamTypeDescription
modelObjectA 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.

Kind: global class

PGConnecter

Postgres Connecter to initialize the singleton for connection.

Kind: global class

new PGConnecter(options)

ParamTypeDefaultDescription
optionsObjectThe connection options.
options.cryptoCryptopostgres/crypto/interface.jsThe implemented crypto interface that follows postgres/crypto/interface.js
options.pgObjectThe options object to pass into pg lib.
options.pg.userStringprocess.env.PGUSERUser's name.
options.pg.passwordStringprocess.env.PGPASSWORDUser's password.
options.pg.databaseStringprocess.env.PGDATABASEDatabase's name.
options.pg.portNumberprocess.env.PGPORTDatabase's port.
options.pg.connectionStringStringPostgres formated connection string. e.g. postgres://user:password@host:5432/database
options.pg.sslTLSSocketOptions to be passed into the native Node.js TLSSocket socket.
options.pg.typespg.typesCustom type parsers. See node-postgres types for more details.
options.pg.statement_timeoutNumber0Number of milliseconds before a statement in query will time out.
options.pg.query_timeoutNumber0number of milliseconds before a query call will timeout.
options.pg.connectionTimeoutMillisNumber0Number of milliseconds to wait before timing out when connecting a new client.
options.pg.idleTimeoutMillisNumber10000Number 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.maxNumber10Maximum 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.

ParamTypeDefaultDescription
strString&#x27;&#x27;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.

ParamTypeDescription
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.

ParamTypeDescription
value\*The value to recursively clone.
[cb]functionThe 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.

ParamTypeDescription
objectObjectThe destination object.
[…sources]ObjectThe 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.

ParamTypeDefaultDescription
funcfunctionThe function to debounce.
delayNumber0The 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.

ParamTypeDescription
collectionArray | ObjectThe collection to iterate over.
cbfunctionThe 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.

ParamTypeDescription
objectObjectThe object to query.
pathArrayThe 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.

ParamTypeDescription
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.

ParamTypeDescription
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.

ParamTypeDefaultDescription
strString&#x27;&#x27;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.

ParamTypeDescription
oObjectThe 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.

ParamTypeDescription
objectObjectThe object to iterate over.
iterateefunctionThe 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.

ParamTypeDefaultDescription
optionsObjectSupports all of nodes HTTP/S Module's options + the folloing.
options.uriStringfully qualified uri.
options.methodStringGEThttp method.
options.headersObject{}http headers.
options.qsObjectobject containing querystring values to be appended to the uri.
options.simpleBooleantruethrows an error for any non 2xx status code response.
options.resolveWithFullResponseBooleanfalseset to true if the full response object is wanted instead of just the body data.
options.qsObjectobject containing querystring values to be appended to the uri.
options.bodyObject | Buffer | String | ReadSteamentity 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.formObjectwhen 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.jsonBooleansetsbody to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON.
options.keepAliveBooleantrueset to false to turn off keepAlive sockets.
options.authorization.basicObjecttakes an object with client and secret props to create a Authorization: Basic client:secret base64 header.
options.authorization.bearerStringcreates a Authorization: Bearer bearer header.
options.redirectMaxNumber5number of times the request will follow a redirect from the server.
options.loggerObjectthe 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.

ParamTypeDescription
objectObjectThe object to modify.
pathArrayThe 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.

ParamTypeDefaultDescription
strString&#x27;&#x27;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.

ParamTypeDescription
valueStringThe value to convert.

Example

toPath('a.b.c');
// => ['a', 'b', 'c']

toPath('a[0].b.c');
// => ['a', '0', 'b', 'c']
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文