diff --git a/src/api/vdi.coffee b/src/api/vdi.coffee index 7ed7afc62..461a59991 100644 --- a/src/api/vdi.coffee +++ b/src/api/vdi.coffee @@ -1,11 +1,10 @@ # FIXME: rename to disk.* $isArray = require 'lodash.isarray' - -#--------------------------------------------------------------------- - {coroutine: $coroutine} = require 'bluebird' +{parseSize} = require '../utils' + #===================================================================== delete_ = $coroutine ({vdi}) -> @@ -34,7 +33,7 @@ set = $coroutine (params) -> # Size. if 'size' of params - {size} = params + size = parseSize(params.size) if size < vdi.size @throw( @@ -65,7 +64,7 @@ set.params = { name_description: { type: 'string', optional: true } # size of VDI - size: { type: 'integer', optional: true } + size: { type: ['integer', 'string'], optional: true } } set.resolve = { diff --git a/src/utils.js b/src/utils.js index dd22907d9..306ac998e 100644 --- a/src/utils.js +++ b/src/utils.js @@ -3,6 +3,7 @@ import forEach from 'lodash.foreach' import has from 'lodash.has' import humanFormat from 'human-format' import isArray from 'lodash.isarray' +import isString from 'lodash.isstring' import multiKeyHashInt from 'multikey-hash' import xml2js from 'xml2js' import {promisify, method} from 'bluebird' @@ -89,6 +90,10 @@ export const pFinally = (promise, cb) => { // ------------------------------------------------------------------- export function parseSize (size) { + if (!isString(size)) { + return size + } + let bytes = humanFormat.parse.raw(size, { scale: 'binary' }) if (bytes.unit && bytes.unit !== 'B') { bytes = humanFormat.parse.raw(size) diff --git a/src/utils.spec.js b/src/utils.spec.js index f8463e150..a36216a8b 100644 --- a/src/utils.spec.js +++ b/src/utils.spec.js @@ -7,7 +7,8 @@ import expect from 'must' import { ensureArray, extractProperty, - formatXml + formatXml, + parseSize } from './utils' // =================================================================== @@ -66,3 +67,25 @@ describe('formatXml()', function () { `) }) }) + +// ------------------------------------------------------------------- + +describe('parseSize()', function () { + it('parses a human size', function () { + expect(parseSize('1G')).to.equal(1e9) + }) + + it('returns the parameter if already a number', function () { + expect(parseSize(1e6)).to.equal(1e6) + }) + + it('throws if the string cannot be parsed', function () { + expect(function () { + parseSize('foo') + }).to.throw() + }) + + it('supports the B unit as suffix', function () { + expect(parseSize('3MB')).to.equal(3e6) + }) +})