All files / src auto.ts

85.18% Statements 23/27
78.57% Branches 11/14
100% Functions 1/1
84.61% Lines 22/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 6122x 22x 22x 22x 22x 22x 22x 22x                                                   22x 13442x 9096x   4346x 1x 75x 9x 4246x   15x 7x   8x     8x     8x             8879x  
import falseValue from './false-value.js'
import json from './json.js'
import nstring from './nstring.js'
import null_ from './null.js'
import number from './number.js'
import raw from './raw.js'
import S from './sanitised.js'
import trueValue from './true-value.js'
 
/**
 * @returns automatically sanitised value.
 *
 * Already sanitised values are returned as is.
 *
 * `undefined` and `null` return sanitised `null`.
 *
 * Finite numbers return sanitised, decimal numbers.
 *
 * Booleans return sanitised `1` (true) or `0` (false).
 *
 * Strings return sanitised unicode strings, ie. `N'foo'`.
 *
 * Dates return ISO strings.
 *
 * Buffers return hex literals.
 *
 * Other objects return json-stringified, sanitised unicode strings, ie. `{foo:1}` returns `N'{"foo":1}'`.
 *
 * @throws {TypeError} for non-finite numbers (not supported by mssql).
 *
 * @throws {TypeError} for all other values.
 */
export const auto =
  (value: unknown): S => {
    if (value instanceof S) {
      return value
    }
    switch (typeof value) {
      case 'undefined': return null_
      case 'number': return number(value)
      case 'boolean': return value ? trueValue : falseValue
      case 'string': return nstring(value)
      case 'object': {
        if (value === null) {
          return null_
        }
        Iif (value instanceof Date) {
          return nstring(value.toISOString())
        }
        Iif (typeof Buffer !== 'undefined' && value instanceof Buffer) {
          return raw('0x' + value.toString('hex'))
        }
        return json(value)
      }
      default:
        throw new TypeError(`Unable to auto generate sql for ${value}.`)
    }
  }
 
export default auto