Electron开发实战之记账软件17——使用Lowdb存储数据

代码仓库: https://github.com/hilanmiao/LanMiaoDesktop

请先阅读这位作者的文章,基本是按照他的思路做的。 https://molunerfinn.com/electron-vue-3/#lowdb%E5%AE%9E%E9%99%85%E4%BD%BF%E7%94%A8%E7%9A%84%E5%9D%91

lodash 中文文档 https://www.html.cn/doc/lodash/ http://lodash.think2011.net/assign

lodash-id 中文文档 https://www.helplib.com/GitHub/article_106283

初始化

核心代码如下:

import Datastore from 'lowdb'
import LodashId from 'lodash-id'
import FileSync from 'lowdb/adapters/FileSync'
import path from 'path'
import fs from 'fs-extra'
// 引入remote模块
import { app, remote } from 'electron'
// package.json
import pkg from '../../package.json'

// 根据process.type来分辨在哪种模式使用哪种模块
const APP = process.type === 'renderer' ? remote.app : app

// 获取electron应用的用户目录
const STORE_PATH = APP.getPath('userData')
// console.log(STORE_PATH)
// C:\Users\JD\AppData\Roaming\Electron

if (process.type !== 'renderer') {
    // 如果不存在路径
    if (!fs.pathExistsSync(STORE_PATH)) {
        // 就创建
        fs.mkdirpSync(STORE_PATH)
    }
}

// 以同步的方式初始化lowdb读写的json文件名以及存储路径
const adapter = new FileSync(path.join(STORE_PATH, `/${pkg.name}_lowdb.json`))

// lowdb接管该文件
const db = Datastore(adapter)
// 通过._mixin()引入lodash_id唯一id插件
db._.mixin(LodashId)

// 初始化数据
if(!db.has('user').value()) {
    db.set('user',[{userId: 'admin', password: '123456'}]).write()
}

if(!db.has('category').value()) {
    db.set('category', []).write()
}

if(!db.has('assets').value()) {
    db.set('assets', []).write()
}

if(!db.has('incomeAndExpenditure').value()) {
    db.set('incomeAndExpenditure', []).write()
}

export default db // 暴露出去

效果: Electron开发实战之记账软件17——使用Lowdb存储数据_第1张图片

Electron开发实战之记账软件17——使用Lowdb存储数据_第2张图片

编写api并使用

结合vuetify的datatable组件做了个CRUD的例子,具体请查看源码。

Electron开发实战之记账软件17——使用Lowdb存储数据_第3张图片

文件结构如下,api也可以放到renderer里,因为我主进程也可能会用到,所以我这边主要把它拿出来了,不一定合适,看个人习惯吧。

Electron开发实战之记账软件17——使用Lowdb存储数据_第4张图片

核心代码如下,insert、upsert、removeWhere等其实都是lodash-id这个模块封装的,你可以点击看看,其实里面的代码还是lodash的,你也可以封装自己的方法。

import db from '../datastore'

export function getCategoryById(id) {
    return new Promise((resolve, reject) => {
        try {
            const collection = db.get('category')
            const category = collection.getById(id).value()
            resolve({
                code: 200,
                data: category
            })
        } catch (err) {
            return reject({
                code: 400,
                message: err.message
            })
        }
    })
}

export function getCategoryWhere(attrs) {
    return new Promise((resolve, reject) => {
        try {
            const collection = db.get('category')
            const categoryList = collection.filter(attrs).value()
            resolve({
                code: 200,
                data: categoryList
            })
        } catch (err) {
            return reject({
                code: 400,
                message: err.message
            })
        }
    })
}

export function getCategoryAll() {
    return new Promise((resolve, reject) => {
        try {
            const collection = db.get('category')
            const categoryAll = collection.value()
            resolve({
                code: 200,
                data: categoryAll
            })
        } catch (err) {
            return reject({
                code: 400,
                message: err.message
            })
        }
    })
}

export function getCategoryPagination(pagination, whereAttrs) {
    return new Promise((resolve, reject) => {
        try {
            const collection = db.get('category')
            const total = collection.size().value()
            const categoryList = collection
                .filter(o => {
                    // 模糊查询
                    return o.category.match(whereAttrs.category)
                })
                .orderBy(pagination.sortBy, pagination.descending ? 'desc' : 'asc')
                .chunk(pagination.rowsPerPage === -1 ? total : pagination.rowsPerPage)
                .take(pagination.page)
                .last() // 因为上面用了chunk,是个二维数组,所以这里取最后一个
                .value()
            resolve({
                code: 200,
                data: {total: total, list: categoryList}
            })
        } catch (err) {
            return reject({
                code: 400,
                message: err.message
            })
        }
    })
}

export function postCategory(document) {
    return new Promise((resolve, reject) => {
        try {
            const collection = db.get('category')
            const category = collection.find({category: document.category}).value()
            if(category) {
                return reject({
                    code: 400,
                    message: 'This classification already exists'
                })
            }
            const newCategory = collection.insert(document).write()
            resolve({
                code: 200,
                data: newCategory
            })
        } catch (err) {
            return reject({
                code: 400,
                message: err.message
            })
        }
    })
}

export function postOrPutCategory(document) {
    return new Promise((resolve, reject) => {
        try {
            const collection = db.get('category')
            if(collection.find({category: document.category}).value()) {
                return reject({
                    code: 400,
                    message: 'This classification already exists'
                })
            }
            const newCategory = collection.upsert(document).write()
            resolve({
                code: 200,
                data: newCategory
            })
        } catch (err) {
            return reject({
                code: 400,
                message: err.message
            })
        }
    })
}

export function putCategoryById(id, attrs) {
    return new Promise((resolve, reject) => {
        try {
            const collection = db.get('category')
            if(collection.find({category: attrs.category}).value()) {
                return reject({
                    code: 400,
                    message: 'This classification already exists'
                })
            }
            const newCategory = collection.updateById(id, attrs).write()
            resolve({
                code: 200,
                data: newCategory
            })
        } catch (err) {
            return reject({
                code: 400,
                message: err.message
            })
        }
    })
}

export function putCategoryWhere(whereAttrs, attrs) {
    return new Promise((resolve, reject) => {
        try {
            const collection = db.get('category')
            if(collection.find({category: attrs.category}).value()) {
                return reject({
                    code: 400,
                    message: 'This classification already exists'
                })
            }
            const newCategory = collection.updateWhere(whereAttrs, attrs).write()
            resolve({
                code: 200,
                data: newCategory
            })
        } catch (err) {
            return reject({
                code: 400,
                message: err.message
            })
        }
    })
}

export function replaceCategoryById(id, attrs) {
    return new Promise((resolve, reject) => {
        try {
            const collection = db.get('category')
            const newCategory = collection.replaceById(id, attrs).write()
            resolve({
                code: 200,
                data: newCategory
            })
        } catch (err) {
            return reject({
                code: 400,
                message: err.message
            })
        }
    })
}

export function deleteCategoryById(id) {
    return new Promise((resolve, reject) => {
        try {
            const collection = db.get('category')
            collection.removeById(id).write()
            resolve({
                code: 200
            })
        } catch (err) {
            return reject({
                code: 400,
                message: err.message
            })
        }
    })
}

export function deleteCategoryByIds(ids) {
    return new Promise((resolve, reject) => {
        try {
            const collection = db.get('category')
            ids.forEach(id => {
                collection.removeById(id).write()
            })
            resolve({
                code: 200
            })
        } catch (err) {
            return reject({
                code: 400,
                message: err.message
            })
        }
    })
}

export function deleteCategoryWhere(whereAttrs) {
    return new Promise((resolve, reject) => {
        try {
            const collection = db.get('category')
            const categoryList = collection.removeWhere(whereAttrs).write()
            resolve({
                code: 200,
                data: categoryList
            })
        } catch (err) {
            return reject({
                code: 400,
                message: err.message
            })
        }
    })
}

说明

  1. 这种微小型数据库,不大可能支持G级,网友说也就是几百MB,所以如果数据量很大,请切换到sqlite。其实写个博客,做个单机小系统足够了,大不了分几个库,反正都是些文件,甚至可以按照日期一天一个文件,当然这样就麻烦了。
  2. 多表查询、分页,emmm,没有这些功能,所有的数据都已经在内存中了,随便折腾就好了......我代码中类似分页这种功能只是在模拟一些动作而已

转载于:https://my.oschina.net/u/3667677/blog/3054535

你可能感兴趣的:(Electron开发实战之记账软件17——使用Lowdb存储数据)