解决本地需要和云端保持文件信息等共存的需求,本地创建数据库,存储字段及其他信息都与云端相同,不相同则同步云端与本地服务,接下来说一下大概的步骤,具体细节可自行查阅相关文档,如有问题,可随时反馈
解释:
sqlite3只作为本地数据库存储
Sequelize
类是引用sequlize
模块后获取一个顶级对象,我们通过它来创建sequlize
实例,也可以通过该对象来获取模内其它对象的引用,如:Utils
工具类、Transaction
事务类等。创建实例后,可以通过实例来创建或定义Model
(模型)、执行查询、同步数据库结构等操作。
一、安装所需依赖包sqlite3及sequelize
安装完sqlite3,需要编译,具体编译方法可参考
二、创建本地数据库步骤
1、创建数据库模型,定义相关存储表字段等
新建dbUtil/model/tResources.js
const resList = (sequelize, DataTypes) => { const resList = sequelize.define("t_resources", { id: {type: DataTypes.STRING, unique: true, allowNull: false,primaryKey: true, defaultValue: ''}, extension: {type: DataTypes.STRING, allowNull: false, defaultValue: ''}, resourceName: {type: DataTypes.STRING, allowNull: false, defaultValue: ''}, addTime: {type: DataTypes.DATE, allowNull: false, defaultValue: ''}, updateTime: {type: DataTypes.DATE, allowNull: false, defaultValue: ''}, }) resList.sync().then(function () { // Table created return resList.create({ id: '11', linkId:"11", resourceName: '测试资源', resourceUrl:'1234', }); }); return resList; } export default { resList }
2、创建数据库(部分代码)
try { //创建数据库 const connect = new Sequelize('database', '', '', Object.assign({}, conf, { host: 'localhost', logging: false, dialect: 'sqlite', storage: dbAbsolutePath, dialectOptions: { // 字符集 charset: "utf8mb4", collate: "utf8mb4_unicode_ci", supportBigNumbers: true, bigNumberStrings: true }, pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } })) // 定义模型 const dbHandle = new dbUtil.DbResList({}, connect) return {dbHandle, connect} } catch (e) { console.log('数据库创建失败',e) throw e }
3、根据model ,可以进行数据的新增,删除,修改等操作
新增
let order = {} order['field'] = vaule order['field'] = (value || 1) Order.create(order)
修改
let order = {}, where = {} where['field'] = value //条件 order['field'] = value //修改的值 Order.update(order, {where})
删除
let where = {} where['field'] = value //条件 Order.destroy({where})
查询
let where ={} Order.findOne({ where, attributes: ['id',...], //查询的字段 include: [{model: User, as: 'user'}] //一对多或者多对一的包含复合查询 })
Sequelize中一些常用的函数
Model.find({ where: { attr1: { gt: 50 }, attr2: { lte: 45 }, attr3: { in: [1,2,3] }, attr4: { ne: 5 } } }) // where条件等价: WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5 Model.find({ where: Sequelize.and( { name: 'a project' }, Sequelize.or( { id: [1,2,3] }, { id: { gt: 10 } } ) ) }) // where条件等价: WHERE name = 'a project' AND (id` IN (1,2,3) OR id > 10)
接下来就是与你的业务进行关联,增删改查等操作,举例如删除一条记录:
/** * 删除一条记录 * @returns {Promise<{trans: *, affectedCount: *}>} */ async destroyRes (options) { const m = this.getResListModel() const result = await this.destroyByModel(m, options) const list = [] for (let item of result.rows) { list.push(this.formatDbObjectToStand(item.toJSON())) } return { affectedCount: result.affectedCount, rows: list } }
/** * see http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-destroy * @returns {Promise<{trans: *, affectedCount: *}>} */ async destroyByModel(model, options) { const condition = Object.assign({}, options) const sequelize = this.sequelizeInstance const m = model await sequelize.sync() try { condition.individualHooks = true const destroyedNumber = await m.destroy(condition) const rowsByCondition = await this.findAllByModel(m, condition) return { rows: rowsByCondition, affectedCount: destroyedNumber } } catch (e) { console.error(e) trans.rollback() throw e } }
以上只贴出来部分代码,具体操作及使用详情如有需要,可添加qq群:856402057 进行详细咨询
交流
我是老礼,公众号「进军全栈攻城狮」作者 ,对前端技术保持学习爱好者。我会经常分享自己所学所看的干货,在进阶的路上,共勉!