vue3+js+lowdb封装,简例
瞎写 写错了告诉我 谢谢
import {Low} from 'lowdb'
import { LocalStorage } from 'lowdb/browser'
import { getUuid } from '@/utils/uuid'
import { cloneDeep } from 'lodash-es'
import { STORE_KEY } from '@/constant'
const adapter = new LocalStorage(STORE_KEY)
const db =new Low(adapter,{
sys: {
public: {},
user: {
'ghost-uuid': {}
}
},
database: {}
})
export default db
export async function pathInit({
dbName = 'database',
path = '',
user = true,
validator = () => true,
defaultValue = ''
}) {
db.read();
let uuid = getUuid()
uuid = uuid === undefined || uuid === null || uuid === '' ? 'ghost-uuid' : (uuid + '')
const currentPath = `${dbName}.${user ? `user.${uuid}` : 'public'}${path ? `.${path}` : ''}`
const value = await getValue(currentPath)
if (!(value !== undefined && validator(value))) {
setValue(currentPath, defaultValue)
}
return currentPath
}
export async function dbSet({
dbName = 'database',
path = '',
value = '',
user = false
}) {
let current = await pathInit({dbName,path,user})
setValue(current, value)
}
async function setValue(path,value){
await db.read();
const keys = path.split('.');
let current = db.data;
for (let i = 0; i < keys.length - 1; i++) {
const key = keys[i];
if (current[key] === undefined) {
current[key] = {};
}
current = current[key];
}
current[keys[keys.length - 1]] = value;
await db.write();
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。