github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/sawtooth-supply-chain-master/asset_client/src/services/parsing.js (about)

     1  /**
     2   * Copyright 2017 Intel Corporation
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   * ----------------------------------------------------------------------------
    16   */
    17  'use strict'
    18  
    19  const _ = require('lodash')
    20  const moment = require('moment')
    21  const { FLOAT_PRECISION } = require('./payloads')
    22  
    23  const STRINGIFIERS = {
    24    LOCATION: v => `${v.latitude}, ${v.longitude}`,
    25    weight: v => `${v}kg`,
    26    temperature: v => `${v} °C`,
    27    shock: v => `${v}g`,
    28    '*': v => JSON.stringify(v, null, 1).replace(/[{}"]/g, '')
    29  }
    30  
    31  /**
    32   * Parses a property value by its name or type, returning a string for display
    33   */
    34  const stringifyValue = (value, type, name) => {
    35    if (STRINGIFIERS[type]) {
    36      return STRINGIFIERS[type](value)
    37    }
    38    if (STRINGIFIERS[name]) {
    39      return STRINGIFIERS[name](value)
    40    }
    41    return STRINGIFIERS['*'](value)
    42  }
    43  
    44  /**
    45   * Simple functions that turn numbers or number-like strings to
    46   * an integer (in millionths) or back to a float.
    47   */
    48  const toFloat = num => parseInt(num) / FLOAT_PRECISION
    49  const toInt = num => parseInt(parseFloat(num) * FLOAT_PRECISION)
    50  
    51  /**
    52   * Calls toFloat on a property value, or it's sub-values in the case of
    53   * an object or JSON object
    54   */
    55  const floatifyValue = value => {
    56    if (_.isString(value)) value = JSON.parse(value)
    57    if (_.isObject(value)) return _.mapValues(value, toFloat)
    58    return toFloat(value)
    59  }
    60  
    61  /**
    62   * Parses seconds into a date/time string
    63   */
    64  const formatTimestamp = sec => {
    65    if (!sec) {
    66      sec = Date.now() / 1000
    67    }
    68    return moment.unix(sec).format('MM/DD/YYYY, h:mm:ss a')
    69  }
    70  
    71  module.exports = {
    72    toInt,
    73    toFloat,
    74    stringifyValue,
    75    floatifyValue,
    76    formatTimestamp
    77  }