the local storage service provides json databases and sqlite databases.
Import Module
const Storage = require('ee-core').Storage;
Json Database
connection
const jdb = Storage.JsonDB.connection('demo');
# or
let lowdbOptions = {
driver: 'lowdb'
}
const jdb = Storage.JsonDB.connection('demo', lowdbOptions);
jdb.setItem()
introduction: Create a stored key/value pair
jdb.setItem('test_key', {name:'xiaoming'})
jdb.getItem()
obtain the stored key value
jdb.getItem('test_key')
jdb.db
introduction: The instantiated lowdb object
- note: lowdb documentation: https://www.npmjs.com/package/lowdb
usage
# 添加对象和数据
db.defaults({posts: [], user: {}, count: 0})
.write();
db.get('posts')
.push({id: 1, title: 'lowdb is awesome'})
.write()
db.set('user.name', 'typicode')
.write()
db.update('count', n => n + 1)
.write()
运行程序会在项目中添加db.json文件,里面存储了添加的数据:
{
"posts": [
{
"id": 1,
"title": "lowdb is awesome"
}
],
"user": {
"name": "typicode"
},
"count": 1
}
you can use any powerful lodash functions, such as.get() and.find(), and can use the following functions in series:
db.get('users')
.find({sex: 'male'})
.value()
query
you can directly use the lodash function to query. Note that some operations may cause the original data to be modified. To avoid such misoperations, you need to use. cloneDeep(). Operations are inert and will only be executed after calling. value() or. write().
Check whether users exist
db.has('users')
.value()
set users
db.set('users', [])
.write()
sort and select
db.get('users')
.filter({sex: 'male'})
.sortBy('age')
.take(5)
.value()
obtain a specific field
db.get('users')
.map('name')
.value()
number obtained
db.get('users')
.size()
.value()
obtain specific information
db.get('users[0].name')
.value()
update information
db.get('users')
.find({name: 'Tom'})
.assign({name: 'Tim'})
.write()
remove Properties
db.unset('users.name)
.write()
deep copy
db.get('users')
.cloneDeep()
.value()
use id index
can be used shortidcreate a unique id index for each record in the database, and then retrieve the operation records by id: ``` const shortid = require(‘shortid’)
const postId = db .get(‘posts’) .push({ id: shortid.generate(), title: ‘low!’ }) .write() .id
const post = db .get(‘posts’) .find({ id: postId }) .value()
<a name="dM3Fx"></a>
### **Sqlite Database **
<a name="iLfey"></a>
#### **connection**
// sqlite let sqliteOptions = { driver: ‘sqlite’, default: { timeout: 6000, verbose: console.log } } const sdb = Storage.JsonDB.connection(‘sqlite-demo.db’, sqliteOptions);
<a name="snM73"></a>
#### sdb.db
add data
const insert = sdb.db.prepare(INSERT INTO ${table} (name, age) VALUES (@name, @age)
);
insert.run(data);
```