Repository URL to install this package:
|
Version:
1.2.12 ▾
|
import { resolve } from 'path'
import { readJSON, read, write, exists } from './readwrite'
const resolveToRoot = x => resolve(process.cwd(), x)
const cachePath = resolveToRoot('./.tmp/cache.json')
const TEMP_PATH = resolveToRoot('./.tmp')
const toSafePath = x => TEMP_PATH + '/' + encodeURIComponent(x) + '.txt'
// create if needed
if (exists(cachePath) === false) {
console.log('CREATING_CACHE')
write(cachePath, {})
}
const cache = readJSON(cachePath)
function save(content = undefined) {
console.log('writing to cache: ', cachePath)
write(cachePath, content === undefined ? cache : content)
return true
}
function getItem(key) {
const cachePathKey = toSafePath(key)
// return key in cache ? stringify(cache[key]) : undefined
return key in cache ? cache[key] : read(cachePathKey)
}
function setItem(key, value) {
cache[key] = value
// fs based cache
const cachePathKey = toSafePath(key)
write(cachePathKey, value)
return true
// return save()
}
function removeItem(key) {
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, value) {
//
}
localStorage.clear = clear
localStorage.removeItem = removeItem
localStorage.setItem = setItem
localStorage.getItem = getItem
localStorage.localStorage = localStorage
if (typeof global === 'object') {
global.localStorage = localStorage
}
Object.defineProperty(localStorage, 'length', {
get() {
return Object.keys(localStorage).length
},
})
Object.defineProperty(localStorage, 'type', {
configurable: false,
enumerable: false,
writable: false,
value: 'server',
})
export { localStorage }
export default localStorage