Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/persistence / src / adapters / server / localStorage.ts
Size: Mime:
import { resolve } from 'path'
import { readJSON, read, write, exists } from './readwrite'
import { Serializable } from '../../deps/stringify'

/**
 * @todo set this.console..
 */
const resolveToRoot = (x: string) => resolve(process.cwd(), x)
const cachePath = resolveToRoot('./.tmp/cache.json')
const TEMP_PATH = resolveToRoot('./.tmp')
const toSafePath = (x: string) =>
  TEMP_PATH + '/' + encodeURIComponent(x) + '.txt'

// create if needed
if (exists(cachePath) === false) {
  console.debug('[persistence]:[server] CREATING_CACHE')
  write(cachePath, {})
}

const cache = readJSON(cachePath)

function save(content: Serializable = undefined) {
  console.debug('[persistence]:[server] writing to cache: ' + cachePath)
  write(cachePath, content === undefined ? cache : content)
  return true
}

function getItem(key: string) {
  const cachePathKey = toSafePath(key)
  // return key in cache ? stringify(cache[key]) : undefined
  return key in cache ? cache[key] : read(cachePathKey)
}

function setItem(key: string, value: Serializable) {
  cache[key] = value

  // fs based cache
  const cachePathKey = toSafePath(key)
  write(cachePathKey, value)

  return true
  // return save()
}

function removeItem(key: string) {
  let found = key in cache
  if (found) {
    return delete cache[key]
  }

  // @todo rimraf

  save()
  return false
}

function clear() {
  Object.keys(cache || {}).forEach(key => {
    delete cache[key]
  })

  return save()
}

function localStorage(key: string, value: Serializable) {
  /**
   * @todo not working yet
   */
}

localStorage.clear = clear
localStorage.removeItem = removeItem
localStorage.setItem = setItem
localStorage.getItem = getItem
localStorage.localStorage = localStorage

/**
 * @todo @fixme globals
 */
if (typeof global === 'object') {
  (global as any).localStorage = localStorage
}

Object.defineProperty(localStorage, 'length', {
  get() {
    return Object.keys(localStorage).length
  },
})

// if (process.env.NODE_ENV === 'test') {
Object.defineProperty(localStorage, 'type', {
  // configurable: false,
  // enumerable: false,
  // writable: false,
  value: 'server',
})

export { localStorage }
export default localStorage