Move often used lodash utils to utils.js

This commit is contained in:
Julien Fontanet 2015-11-09 12:03:34 +01:00
parent be35693814
commit 0eb949ba39
21 changed files with 92 additions and 66 deletions

View File

@ -2,7 +2,6 @@ import createDebug from 'debug'
const debug = createDebug('xo:api') const debug = createDebug('xo:api')
import assign from 'lodash.assign' import assign from 'lodash.assign'
import forEach from 'lodash.foreach'
import getKeys from 'lodash.keys' import getKeys from 'lodash.keys'
import isFunction from 'lodash.isfunction' import isFunction from 'lodash.isfunction'
import kindOf from 'kindof' import kindOf from 'kindof'
@ -15,7 +14,10 @@ import {
NoSuchObject, NoSuchObject,
Unauthorized Unauthorized
} from './api-errors' } from './api-errors'
import { createRawObject } from './utils' import {
createRawObject,
forEach
} from './utils'
// =================================================================== // ===================================================================

View File

@ -1,5 +1,8 @@
import forEach from 'lodash.foreach' import {
import {ensureArray, parseXml} from '../utils' ensureArray,
forEach,
parseXml
} from '../utils'
// =================================================================== // ===================================================================

View File

@ -1,6 +1,5 @@
import map from 'lodash.map'
import {InvalidParameters} from '../api-errors' import {InvalidParameters} from '../api-errors'
import { mapToArray } from '../utils'
// =================================================================== // ===================================================================
@ -49,7 +48,7 @@ export async function getAll () {
const users = await this._users.get() const users = await this._users.get()
// Filters out private properties. // Filters out private properties.
return map(users, this.getUserPublicProperties) return mapToArray(users, this.getUserPublicProperties)
} }
getAll.description = 'returns all the existing users' getAll.description = 'returns all the existing users'

View File

@ -2,13 +2,11 @@ $debug = (require 'debug') 'xo:api:vm'
$filter = require 'lodash.filter' $filter = require 'lodash.filter'
$findIndex = require 'lodash.findindex' $findIndex = require 'lodash.findindex'
$findWhere = require 'lodash.find' $findWhere = require 'lodash.find'
$forEach = require 'lodash.foreach'
$isArray = require 'lodash.isarray' $isArray = require 'lodash.isarray'
endsWith = require 'lodash.endswith' endsWith = require 'lodash.endswith'
escapeStringRegexp = require 'escape-string-regexp' escapeStringRegexp = require 'escape-string-regexp'
eventToPromise = require 'event-to-promise' eventToPromise = require 'event-to-promise'
got = require('got') got = require('got')
map = require 'lodash.map'
sortBy = require 'lodash.sortby' sortBy = require 'lodash.sortby'
startsWith = require 'lodash.startswith' startsWith = require 'lodash.startswith'
{coroutine: $coroutine} = require 'bluebird' {coroutine: $coroutine} = require 'bluebird'
@ -19,7 +17,9 @@ startsWith = require 'lodash.startswith'
Unauthorized Unauthorized
} = require('../api-errors') } = require('../api-errors')
{ {
forEach,
formatXml: $js2xml, formatXml: $js2xml,
mapToArray,
parseXml, parseXml,
pFinally pFinally
} = require '../utils' } = require '../utils'

View File

@ -2,13 +2,15 @@ import Bluebird from 'bluebird'
import Collection, {ModelAlreadyExists} from '../collection' import Collection, {ModelAlreadyExists} from '../collection'
import difference from 'lodash.difference' import difference from 'lodash.difference'
import filter from 'lodash.filter' import filter from 'lodash.filter'
import forEach from 'lodash.foreach'
import getKey from 'lodash.keys' import getKey from 'lodash.keys'
import isEmpty from 'lodash.isempty'
import map from 'lodash.map'
import {createClient as createRedisClient, RedisClient, Multi} from 'redis' import {createClient as createRedisClient, RedisClient, Multi} from 'redis'
import {promisifyAll} from '../utils' import {
forEach,
isEmpty,
mapToArray,
promisifyAll
} from '../utils'
// =================================================================== // ===================================================================
@ -146,7 +148,7 @@ export default class Redis extends Collection {
throw new Error('fields not indexed: ' + unfit.join()) throw new Error('fields not indexed: ' + unfit.join())
} }
const keys = map(properties, (value, index) => prefix + '_' + index + ':' + value) const keys = mapToArray(properties, (value, index) => `${prefix}_${index}:${value}`)
return redis.sinterAsync(...keys).then(ids => this._extract(ids)) return redis.sinterAsync(...keys).then(ids => this._extract(ids))
} }
@ -160,7 +162,7 @@ export default class Redis extends Collection {
redis.sremAsync(prefix + '_ids', ...ids), redis.sremAsync(prefix + '_ids', ...ids),
// Remove the models. // Remove the models.
redis.delAsync(map(ids, id => prefix + ':' + id)) redis.delAsync(mapToArray(ids, id => `${prefix}:${id}`))
]) ])
} }

View File

@ -7,11 +7,9 @@ import bind from 'lodash.bind'
import blocked from 'blocked' import blocked from 'blocked'
import createExpress from 'express' import createExpress from 'express'
import eventToPromise from 'event-to-promise' import eventToPromise from 'event-to-promise'
import forEach from 'lodash.foreach'
import has from 'lodash.has' import has from 'lodash.has'
import isArray from 'lodash.isarray' import isArray from 'lodash.isarray'
import isFunction from 'lodash.isfunction' import isFunction from 'lodash.isfunction'
import map from 'lodash.map'
import pick from 'lodash.pick' import pick from 'lodash.pick'
import proxyConsole from './proxy-console' import proxyConsole from './proxy-console'
import proxyRequest from 'proxy-http-request' import proxyRequest from 'proxy-http-request'
@ -37,7 +35,11 @@ import Scheduler from './scheduler'
import WebServer from 'http-server-plus' import WebServer from 'http-server-plus'
import wsProxy from './ws-proxy' import wsProxy from './ws-proxy'
import Xo from './xo' import Xo from './xo'
import { createRawObject } from './utils' import {
createRawObject,
forEach,
mapToArray
} from './utils'
import bodyParser from 'body-parser' import bodyParser from 'body-parser'
import connectFlash from 'connect-flash' import connectFlash from 'connect-flash'
@ -248,7 +250,7 @@ async function registerPlugin (pluginConf, pluginName) {
} }
function registerPlugins (plugins, xo) { function registerPlugins (plugins, xo) {
return Promise.all(map(plugins, (conf, name) => { return Promise.all(mapToArray(plugins, (conf, name) => {
return registerPlugin.call(xo, conf, name).then( return registerPlugin.call(xo, conf, name).then(
() => { () => {
debugPlugin(`successfully register ${name}`) debugPlugin(`successfully register ${name}`)
@ -292,7 +294,7 @@ async function makeWebServerListen (opts) {
async function createWebServer (opts) { async function createWebServer (opts) {
const webServer = new WebServer() const webServer = new WebServer()
await Promise.all(map(opts, makeWebServerListen, webServer)) await Promise.all(mapToArray(opts, makeWebServerListen, webServer))
return webServer return webServer
} }

View File

@ -1,8 +1,10 @@
import assign from 'lodash.assign' import assign from 'lodash.assign'
import forEach from 'lodash.foreach'
import {BaseError} from 'make-error' import {BaseError} from 'make-error'
import {createRawObject} from './utils' import {
createRawObject,
forEach
} from './utils'
export class JobExecutorError extends BaseError {} export class JobExecutorError extends BaseError {}
export class UnsupportedJobType extends JobExecutorError { export class UnsupportedJobType extends JobExecutorError {

View File

@ -1,8 +1,11 @@
import assign from 'lodash.assign' import assign from 'lodash.assign'
import forEach from 'lodash.foreach'
import isEmpty from 'lodash.isempty'
import {EventEmitter} from 'events' import {EventEmitter} from 'events'
import {
forEach,
isEmpty
} from './utils'
// =================================================================== // ===================================================================
export default class Model extends EventEmitter { export default class Model extends EventEmitter {

View File

@ -1,9 +1,10 @@
import forEach from 'lodash.foreach'
import map from 'lodash.map'
import Collection from '../collection/redis' import Collection from '../collection/redis'
import Model from '../model' import Model from '../model'
import {multiKeyHash} from '../utils' import {
forEach,
mapToArray,
multiKeyHash
} from '../utils'
// =================================================================== // ===================================================================
@ -58,11 +59,11 @@ export class Acls extends Collection {
}) })
if (toUpdate.length) { if (toUpdate.length) {
// Removes all existing entries. // Removes all existing entries.
await this.remove(map(toUpdate, 'id')) await this.remove(mapToArray(toUpdate, 'id'))
// Compute the new ids (new hashes). // Compute the new ids (new hashes).
const {hash} = Acl const {hash} = Acl
await Promise.all(map( await Promise.all(mapToArray(
toUpdate, toUpdate,
(acl) => hash(acl.subject, acl.object, acl.action).then(id => { (acl) => hash(acl.subject, acl.object, acl.action).then(id => {
acl.id = id acl.id = id

View File

@ -1,8 +1,8 @@
import forEach from 'lodash.foreach'
import Collection from '../collection/redis' import Collection from '../collection/redis'
import Model from '../model' import Model from '../model'
import { forEach } from '../utils'
// =================================================================== // ===================================================================
export default class Group extends Model {} export default class Group extends Model {}

View File

@ -1,7 +1,6 @@
import forEach from 'lodash.foreach'
import Collection from '../collection/redis' import Collection from '../collection/redis'
import Model from '../model' import Model from '../model'
import { forEach } from '../utils'
// =================================================================== // ===================================================================

View File

@ -1,8 +1,8 @@
import assign from 'lodash.assign' import assign from 'lodash.assign'
import forEach from 'lodash.foreach'
import Collection from '../collection/redis' import Collection from '../collection/redis'
import Model from '../model' import Model from '../model'
import { forEach } from '../utils'
// =================================================================== // ===================================================================

View File

@ -1,6 +1,6 @@
import Collection from '../collection/redis' import Collection from '../collection/redis'
import forEach from 'lodash.foreach'
import Model from '../model' import Model from '../model'
import { forEach } from '../utils'
// =================================================================== // ===================================================================

View File

@ -1,6 +1,6 @@
import Collection from '../collection/redis' import Collection from '../collection/redis'
import forEach from 'lodash.foreach'
import Model from '../model' import Model from '../model'
import { forEach } from '../utils'
// =================================================================== // ===================================================================

View File

@ -1,8 +1,8 @@
import forEach from 'lodash.foreach'
import { hash } from 'hashy' import { hash } from 'hashy'
import Collection from '../collection/redis' import Collection from '../collection/redis'
import Model from '../model' import Model from '../model'
import { forEach } from '../utils'
// =================================================================== // ===================================================================

View File

@ -1,9 +1,11 @@
import filter from 'lodash.filter' import filter from 'lodash.filter'
import forEach from 'lodash.foreach'
import fs from 'fs-promise' import fs from 'fs-promise'
import {exec} from 'child_process' import {exec} from 'child_process'
import {promisify} from './utils' import {
forEach,
promisify
} from './utils'
const execAsync = promisify(exec) const execAsync = promisify(exec)

View File

@ -1,7 +1,8 @@
import forEach from 'lodash.foreach'
import {BaseError} from 'make-error' import {BaseError} from 'make-error'
import {CronJob} from 'cron' import {CronJob} from 'cron'
import { forEach } from './utils'
const _resolveId = scheduleOrId => scheduleOrId.id || scheduleOrId const _resolveId = scheduleOrId => scheduleOrId.id || scheduleOrId
export class SchedulerError extends BaseError {} export class SchedulerError extends BaseError {}

View File

@ -171,6 +171,15 @@ export const safeDateFormat = d3TimeFormat('%Y%m%dT%H%M%SZ')
// ------------------------------------------------------------------- // -------------------------------------------------------------------
// This functions are often used throughout xo-server.
//
// Exports them from here to avoid direct dependencies on lodash.
export { default as forEach } from 'lodash.foreach'
export { default as isEmpty } from 'lodash.isempty'
export { default as mapToArray } from 'lodash.map'
// -------------------------------------------------------------------
// Special value which can be returned to stop an iteration in map() // Special value which can be returned to stop an iteration in map()
// and mapInPlace(). // and mapInPlace().
export const DONE = {} export const DONE = {}

View File

@ -1,10 +1,10 @@
import forEach from 'lodash.foreach'
import isArray from 'lodash.isarray' import isArray from 'lodash.isarray'
import map from 'lodash.map'
import { import {
ensureArray, ensureArray,
extractProperty, extractProperty,
forEach,
mapToArray,
parseXml parseXml
} from './utils' } from './utils'
import { import {
@ -23,7 +23,7 @@ function link (obj, prop, idField = '$id') {
} }
if (isArray(dynamicValue)) { if (isArray(dynamicValue)) {
return map(dynamicValue, idField) return mapToArray(dynamicValue, idField)
} }
return dynamicValue[idField] return dynamicValue[idField]

View File

@ -5,10 +5,8 @@ import escapeStringRegexp from 'escape-string-regexp'
import eventToPromise from 'event-to-promise' import eventToPromise from 'event-to-promise'
import filter from 'lodash.filter' import filter from 'lodash.filter'
import find from 'lodash.find' import find from 'lodash.find'
import forEach from 'lodash.foreach'
import got from 'got' import got from 'got'
import includes from 'lodash.includes' import includes from 'lodash.includes'
import map from 'lodash.map'
import sortBy from 'lodash.sortby' import sortBy from 'lodash.sortby'
import unzip from 'julien-f-unzip' import unzip from 'julien-f-unzip'
import { PassThrough } from 'stream' import { PassThrough } from 'stream'
@ -24,7 +22,10 @@ import {
camelToSnakeCase, camelToSnakeCase,
createRawObject, createRawObject,
ensureArray, ensureArray,
noop, parseXml, forEach,
mapToArray,
noop,
parseXml,
pFinally, pFinally,
safeDateFormat safeDateFormat
} from './utils' } from './utils'
@ -228,7 +229,7 @@ export default class Xapi extends XapiBase {
// TODO: the thrown error should contain the name of the // TODO: the thrown error should contain the name of the
// properties that failed to be set. // properties that failed to be set.
await Promise.all(map(props, (value, name) => { await Promise.all(mapToArray(props, (value, name) => {
if (value != null) { if (value != null) {
return this.call(`${namespace}.set_${camelToSnakeCase(name)}`, ref, value) return this.call(`${namespace}.set_${camelToSnakeCase(name)}`, ref, value)
} }
@ -302,10 +303,10 @@ export default class Xapi extends XapiBase {
name: patch['name-label'], name: patch['name-label'],
url: patch['patch-url'], url: patch['patch-url'],
uuid: patch.uuid, uuid: patch.uuid,
conflicts: map(ensureArray(patch.conflictingpatches), patch => { conflicts: mapToArray(ensureArray(patch.conflictingpatches), patch => {
return patch.conflictingpatch.uuid return patch.conflictingpatch.uuid
}), }),
requirements: map(ensureArray(patch.requiredpatches), patch => { requirements: mapToArray(ensureArray(patch.requiredpatches), patch => {
return patch.requiredpatch.uuid return patch.requiredpatch.uuid
}) })
// TODO: what does it mean, should we handle it? // TODO: what does it mean, should we handle it?
@ -406,7 +407,7 @@ export default class Xapi extends XapiBase {
async listMissingPoolPatchesOnHost (hostId) { async listMissingPoolPatchesOnHost (hostId) {
// Returns an array to not break compatibility. // Returns an array to not break compatibility.
return map( return mapToArray(
await this._listMissingPoolPatchesOnHost(this.getObject(hostId)) await this._listMissingPoolPatchesOnHost(this.getObject(hostId))
) )
} }
@ -678,7 +679,7 @@ export default class Xapi extends XapiBase {
// Creates the VDIs. // Creates the VDIs.
// //
// TODO: set vm.suspend_SR // TODO: set vm.suspend_SR
await Promise.all(map(vdis, (vdiDescription, i) => { await Promise.all(mapToArray(vdis, (vdiDescription, i) => {
return this._createVdi( return this._createVdi(
vdiDescription.size, vdiDescription.size,
{ {
@ -695,12 +696,12 @@ export default class Xapi extends XapiBase {
})) }))
// Destroys the VIFs cloned from the template. // Destroys the VIFs cloned from the template.
await Promise.all(map(vm.$vifs, vif => this._deleteVif(vif))) await Promise.all(mapToArray(vm.$vifs, vif => this._deleteVif(vif)))
// Creates the VIFs specified by the user. // Creates the VIFs specified by the user.
{ {
let position = 0 let position = 0
await Promise.all(map(vifs, vif => this._createVif( await Promise.all(mapToArray(vifs, vif => this._createVif(
vm, vm,
this.getObject(vif.network), this.getObject(vif.network),
{ {
@ -726,7 +727,7 @@ export default class Xapi extends XapiBase {
} }
if (deleteDisks) { if (deleteDisks) {
await Promise.all(map(vm.$VBDs, vbd => { await Promise.all(mapToArray(vm.$VBDs, vbd => {
// DO not remove CDs and Floppies. // DO not remove CDs and Floppies.
if (vbd.type === 'Disk') { if (vbd.type === 'Disk') {
return this._deleteVdi(vbd.$VDI).catch(noop) return this._deleteVdi(vbd.$VDI).catch(noop)
@ -734,7 +735,7 @@ export default class Xapi extends XapiBase {
})) }))
} }
await Promise.all(map(vm.$snapshots, snapshot => { await Promise.all(mapToArray(vm.$snapshots, snapshot => {
return this.deleteVm(snapshot.$id, true).catch(noop) return this.deleteVm(snapshot.$id, true).catch(noop)
})) }))

View File

@ -6,13 +6,10 @@ import endsWith from 'lodash.endswith'
import escapeStringRegexp from 'escape-string-regexp' import escapeStringRegexp from 'escape-string-regexp'
import eventToPromise from 'event-to-promise' import eventToPromise from 'event-to-promise'
import filter from 'lodash.filter' import filter from 'lodash.filter'
import forEach from 'lodash.foreach'
import fs from 'fs-promise' import fs from 'fs-promise'
import includes from 'lodash.includes' import includes from 'lodash.includes'
import isEmpty from 'lodash.isempty'
import isFunction from 'lodash.isfunction' import isFunction from 'lodash.isfunction'
import isString from 'lodash.isstring' import isString from 'lodash.isstring'
import map from 'lodash.map'
import sortBy from 'lodash.sortby' import sortBy from 'lodash.sortby'
import startsWith from 'lodash.startswith' import startsWith from 'lodash.startswith'
import XoCollection from 'xo-collection' import XoCollection from 'xo-collection'
@ -33,6 +30,9 @@ import {Acls} from './models/acl'
import {autobind} from './decorators' import {autobind} from './decorators'
import { import {
createRawObject, createRawObject,
forEach,
isEmpty,
mapToArray,
safeDateFormat safeDateFormat
} from './utils' } from './utils'
import {generateToken} from './utils' import {generateToken} from './utils'
@ -233,7 +233,7 @@ export default class Xo extends EventEmitter {
})(acls.push) })(acls.push)
const {_acls: collection} = this const {_acls: collection} = this
await Promise.all(map( await Promise.all(mapToArray(
subjects, subjects,
subject => collection.get({subject}).then(pushAcls) subject => collection.get({subject}).then(pushAcls)
)) ))
@ -488,8 +488,8 @@ export default class Xo extends EventEmitter {
}) })
const [newUsers, oldUsers] = await Promise.all([ const [newUsers, oldUsers] = await Promise.all([
Promise.all(map(newUsersIds, (_, id) => this.getUser(id))), Promise.all(mapToArray(newUsersIds, (_, id) => this.getUser(id))),
Promise.all(map(oldUsersIds, (_, id) => this.getUser(id))) Promise.all(mapToArray(oldUsersIds, (_, id) => this.getUser(id)))
]) ])
forEach(newUsers, user => { forEach(newUsers, user => {
@ -505,8 +505,8 @@ export default class Xo extends EventEmitter {
group.users = userIds group.users = userIds
await Promise.all([ await Promise.all([
Promise.all(map(newUsers, this._users.save, this._users)), Promise.all(mapToArray(newUsers, this._users.save, this._users)),
Promise.all(map(oldUsers, this._users.save, this._users)), Promise.all(mapToArray(oldUsers, this._users.save, this._users)),
this._groups.save(group) this._groups.save(group)
]) ])
} }
@ -662,7 +662,7 @@ export default class Xo extends EventEmitter {
} }
async getAllRemotes () { async getAllRemotes () {
return map(await this._remotes.get(), this._developRemote) return mapToArray(await this._remotes.get(), this._developRemote)
} }
async _getRemote (id) { async _getRemote (id) {
@ -1321,7 +1321,7 @@ export default class Xo extends EventEmitter {
async getPlugins () { async getPlugins () {
return await Promise.all( return await Promise.all(
map(this._plugins, ({ id }) => this._getPlugin(id)) mapToArray(this._plugins, ({ id }) => this._getPlugin(id))
) )
} }