All files / src/aws name.ts

100% Statements 25/25
92.86% Branches 13/14
100% Functions 19/19
100% Lines 25/25
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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109  5x 5x 5x 5x                 38x     38x     120x       9x     3x     3x     3x     3x     3x     3x     5x     5x 5x     7x     10x     8x     8x     30x             30x     30x               5x                                                      
import * as md5 from 'md5'
import * as util from 'util'
 
const TEXT = {
  DIMENSION: 'dynamodb:%s:%sCapacityUnits',
  METRIC: 'DynamoDB%sCapacityUtilization',
  POLICYROLE: 'DynamoDBAutoscalePolicy',
  POLICYSCALE: 'TableScalingPolicy-%s',
  ROLE: 'DynamoDBAutoscaleRole',
  TARGET: 'AutoScalingTarget-%s'
}
 
function clean(input: string): string {
  return truncate(input.replace(/[^a-z0-9+]+/gi, ''))
}
 
function truncate(input: string): string {
  return input.length <= 64 ? input : input.substr(0, 32) + md5(input)
}
 
function ucfirst(data: string): string {
  return data.charAt(0).toUpperCase() + data.slice(1)
}
 
export default class Name {
  constructor(private options: Options) { }
 
  public metricRead(): string {
    return this.metric(true)
  }
 
  public metricWrite(): string {
    return this.metric(false)
  }
 
  public targetRead(): string {
    return this.target(true)
  }
 
  public targetWrite(): string {
    return this.target(false)
  }
 
  public policyScaleRead(): string {
    return this.policyScale(true)
  }
 
  public policyScaleWrite(): string {
    return this.policyScale(false)
  }
 
  public policyRole(): string {
    return clean(
      this.build(TEXT.POLICYROLE)
    )
  }
 
  public dimension(read: boolean): string {
    const type = this.options.index === '' ? 'table' : 'index'
 
    return util.format(TEXT.DIMENSION, type, read ? 'Read' : 'Write')
  }
 
  public role(): string {
    return clean(this.build(TEXT.ROLE))
  }
 
  public target(read: boolean): string {
    return clean(
      this.build(TEXT.TARGET, read ? 'Read' : 'Write')
    )
  }
 
  public policyScale(read: boolean): string {
    return clean(
      this.build(TEXT.POLICYSCALE, read ? 'Read' : 'Write')
    )
  }
 
  public metric(read: boolean): string {
    return clean(
      util.format(TEXT.METRIC, read ? 'Read' : 'Write')
    )
  }
 
  private build(data: string, ...args: string[]): string {
    return [
      this.prefix(),
      args ? util.format(data, ...args) : data,
      this.suffix()
    ].join('')
  }
 
  private prefix(): string {
    return this.options.service
  }
 
  private suffix(): string {
    return [
      this.options.table,
      this.options.index,
      this.options.stage,
      this.options.region
    ].map(
      ucfirst
    ).join('')
  }
}