序文
フロントエンド開発者として、Web サイトを構築するとき、以下に示すように、小さな公式 Web サイト、登録なし、ログインなし、1 つの提案のみなど、データを保存する必要があるシナリオに必然的に遭遇します。保存する必要がある Web サイト上の 1 つの場所のみ
. データを入力します。
シーン
ウェブサイトは、登録してログインするだけで、提案を行い、私たちに連絡するなど、ほとんどデータを保存する必要がありません. データの永続化を行う場合、コストの問題を考慮する必要があります.データベースを使用せずにいくつかの軽量ソリューションを使用できます.
少しの酢だけで餃子を作ることはできません。そして、これらのデータを保存するためにデータベースが使用されると、学習コストと保守コストの両方が比較的大きくなります。
賢い人は、最善の解決策を選ぶのではなく、常に最適な解決策を選択します。これは、コストを削減し、効率を高める重要な手段でもあります。
使い方
このような単純なビジネス シナリオでデータの永続性をすばやく実現する方法を紹介します。この記事では、データを json ファイル形式でローカルに保存し、nodejs で使用できる
オープン ソース ライブラリを使用します。node-json-db
ライブラリの github アドレス https://github.com/Belphemur/node-json-db
コマンドを使用してプロジェクトにインストールします
yarn add node-json-db
このライブラリについては、注釈付きのコードに従って学習できます。
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();
より多くのケース挿入配列の処理
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);
上記の API に基づいて、簡単な登録、ログイン、および単一の関数の作成を実装しました。使用上の問題を確認するため。以下は筆者が書いたコードです。
完全なコード
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;
使用上の最大の問題は、依然としてさまざまな便利なクエリ メソッドです。単純なクエリしか扱えず、複雑なクエリを実現するには二次的なデータ処理や開発が必要です。
あとがき
ローカル json ファイルにデータを保存するこのスキームをマスターすると、作業が非常にシンプルで便利になります。