All files / src reference.ts

57.14% Statements 16/28
50% Branches 2/4
46.15% Functions 6/13
60% Lines 15/25

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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 771x   1x     1x   17x 5x       12x                 1x 17x 17x               8x       16x       24x       11x 11x       1x                                                        
import * as R from 'ramda'
import { ReferenceStorage } from './types/reference-storage'
import * as ObjectPath from 'object-path'
 
 
export abstract class Reference {
  static from($ref: string | string[]): Reference {
    if (typeof $ref === 'string') {
      if ($ref.startsWith('#')) return new RelativeReference($ref.split('/').slice(1))
      return new AbsoluteReference($ref)
    }
 
    return new RelativeReference($ref)
  }
 
  abstract toString(): string
  abstract set<T>(storage: ReferenceStorage<T>, value: T): void
  abstract get<T>(storage: ReferenceStorage<T>): T | undefined
  abstract equals(ref: Reference): boolean
}
 
export class RelativeReference extends Reference {
  constructor(private paths: string[]) {
    super()
  }
 
  async resolve<T>(object: object): Promise<T | undefined> {
    return R.pathOr(undefined, this.paths, object)
  }
 
  toString(): string {
    return `#/${this.paths.join('/')}`
  }
 
  set<T>(storage: ReferenceStorage<T>, value: T): void {
    ObjectPath.set(storage, this.paths, value)
  }
 
  get<T>(storage: ReferenceStorage<T>): T | undefined {
    return R.path(this.paths, storage)
  }
 
  equals(ref: Reference): boolean {
    Iif (!(ref instanceof RelativeReference)) return false
    return R.equals(this.paths, ref.paths)
  }
}
 
export class AbsoluteReference extends Reference {
  constructor(private address: string) {
    super()
  }
 
  async resolve<T>(): Promise<T | undefined> {
    throw new Error('Not implemented')
  }
 
  toString(): string {
    return this.address
  }
 
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  set<T>(storage: ReferenceStorage<T>, value: T): void {
    throw new Error('AbsoluteReference is not supported')
  }
 
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  get<T>(storage: ReferenceStorage<T>): T | undefined {
    throw new Error('AbsoluteReference is not supported')
  }
 
  equals(ref: Reference): boolean {
    Iif (!(ref instanceof AbsoluteReference)) return false
    return this.address === ref.address
  }
}