The lightweight data persistence solution of the nodejs project, node-json-db, directly uses json files to save and query data.

foreword

As a front-end developer, when we build a website, we will inevitably encounter scenarios where we need to save data, such as a small official website, no registration, no login, and only one suggestion for us, as shown below, there is only one place on the website that needs to be saved
insert image description here
. Fill in the data.

Scenes

The website needs to save very little data, such as only registering and logging in and making suggestions and contacting us. When we do data persistence, we need to consider the issue of cost. We can use some lightweight solutions without using a database.
We can't just make dumplings for a little vinegar. And once the database is used to save these data, both the learning cost and the maintenance cost are relatively large.

Smart people don't choose the best solution, they always choose the most suitable solution. This is also an important means of reducing costs and increasing efficiency.

How to use

Let me introduce how to quickly realize data persistence in such a simple business scenario.
In this article, I use an open source library node-json-db, which can save data locally in json file format and use it in nodejs.

The github address of the library https://github.com/Belphemur/node-json-db

Install in your project with the command

yarn add node-json-db

You can learn about this library by following the annotated code.

import {
    
     JsonDB, Config } from 'node-json-db';

// 第一个参数是数据库文件名。如果没有写扩展名,则默认为“.json”并自动添加。
// 第二个参数用于告诉数据库在每次推送后保存,如果设置false,则必须手动调用save()方法。
// 第三个参数是要求JsonDB以人类可读的格式保存数据库。(默认为false)
// 最后一个参数是分隔符。默认情况下为斜线(/) 
var db = new JsonDB(new Config("myDataBase", true, false, '/'));

// 将数据推入数据库
// 使用想要的的数据路径
// 默认情况下,新值将覆盖旧的值
await db.push("/test1","super test");

// 如果数据路径不存在,它将在推送新数据时自动创建层次结构
await db.push("/test2/my/test",5);

// 你可以直接推送一个多层的json对象
await db.push("/test3", {
    
    test:"test", json: {
    
    test:["test"]}});

// 如果你希望在推送数据时不是覆盖旧值,而是合并它们。你可以设置push方法的第二个参数为false。
// 合并是递归的,可以使用Object和Array。
await db.push("/test3", {
    
    
    new:"cool",
    json: {
    
    
        important : 5
    }
}, false);

/*
最终结果
{
   "test":"test",
   "json":{
      "test":[
         "test"
      ],
      "important":5
   },
   "new":"cool"
}
*/

// 你无法合并原始值,像下面这样,数据将会被覆盖
await db.push("/test2/my/test/",10,false);
 
// 获取根路径下的所有数据
var data = await db.getData("/");

// 从一个数据路径中获取数据
var data = await db.getData("/test1");

// 如果你无法确认数据路径是否存在,可以使用tr catch来包裹它,如果不存在,将进入catch块中。
try {
    
    
    var data = await db.getData("/test1/test/dont/work");
} catch(error) {
    
    
    // The error will tell you where the DataPath stopped. In this case test1
    // Since /test1/test does't exist.
    console.error(error);
};

 
// 删除数据
await db.delete("/test1");

// 保存数据,如果你禁用了在推送时保存。
await db.save();

// 为了防止数据库文件被外部修改,你可以使用reload(),方法重载数据库文件,以此获取最新的数据。
await db.reload();

Handling of more case injection arrays

import {
    
     JsonDB, Config } from 'node-json-db';

// The first argument is the database filename. If no extension, '.json' is assumed and automatically added.
// The second argument is used to tell the DB to save after each push
// If you put false, you'll have to call the save() method.
// The third argument is to ask JsonDB to save the database in an human readable format. (default false)
const db = new JsonDB(new Config("myDataBase", true, false, '/'));

// This will create an array 'myarray' with the object '{obj:'test'}' at index 0
await db.push("/arraytest/myarray[0]", {
    
    
    obj:'test'
}, true);

// You can retrieve a property of an object included in an array
// testString = 'test';
var testString = await db.getData("/arraytest/myarray[0]/obj");

// Doing this will delete the object stored at the index 0 of the array.
// Keep in mind this won't delete the array even if it's empty.
await db.delete("/arraytest/myarray[0]");

// You can also easily append new item to an existing array
// This set the next index with {obj: 'test'}
await db.push("/arraytest/myarray[]", {
    
    
    obj:'test'
}, true);


// The append feature can be used in conjuction with properties
// This will set the next index as an object {myTest: 'test'}
await db.push("/arraytest/myarray[]/myTest", 'test', true);

Based on the above api, I implemented a simple registration, login, and create a single function. In order to verify the problem in use. The following is the code written by the author.

full code

var express = require('express');
var router = express.Router();
const {
    
     JsonDB, Config } = require('node-json-db');
const db = new JsonDB(new Config("cardshop", true, false, '/'));
const successInfo = {
    
     code: 200, msg: 'success' }

/* POST 登录 */
router.post('/login', async function (req, res, next) {
    
    
  const {
    
     username, password, vertify } = req.body
  try {
    
    
    var data = await db.getData(`/${
      
      username}`);
    if (data.password === password) {
    
    
      res.json(successInfo)
    } else {
    
    
      res.json({
    
     code: 403, msg: '账号或密码不匹配' })
    }
  } catch (error) {
    
    
    res.json({
    
     code: 403, msg: '账号或密码不匹配' })
  };
});

/* POST 注册 */
router.post('/register', async function (req, res, next) {
    
    
  console.log(req.body, 'req.body')
  const {
    
     username } = req.body
  const userModel = {
    
     ...req.body }
  userModel.createTime = new Date()
  userModel.orders = []
  await db.push(`/${
      
      username}`, userModel);
  res.json(successInfo)
});

/* POST 创建一个订单 */
router.post('/createOrder', async function (req, res, next) {
    
    
  const {
    
     username } = req.body
  const orderModel = {
    
     ...req.body }
  orderModel.createTime = new Date()
  await db.push(`/${
      
      username}/orders[]`, orderModel);
  res.json(successInfo)
});

module.exports = router;

The biggest problem in use may still be the various convenient query methods. It can only deal with simple queries. To realize complex queries, secondary data processing or development is required.

postscript

Mastering this scheme of saving data in local json files can make our work very simple and convenient.

Guess you like

Origin blog.csdn.net/github_35631540/article/details/130165402