【前端必会】使用indexedDB,降低环境搭建成本

  • Post category:JavaScript

背景

  1. 学习前端新框架、新技术。如果需要做一些数据库的操作来增加demo的体验(CURD流程可以让演示的体验根据丝滑)
  2. 最开始的时候一个演示程序我们会调用后台,这样其实有一点弊端,就是增加了开发和维护成本,简单的一个demo不应该劳师动众
  3. 后来我会在demo中使用一些websql,奈何,websql也真的是没前景了。代码写起来也不是特别好
  4. 下面来介绍下今天的主角indexedDB和jsStore

介绍

  1. indexedDB可以给浏览器本地存储的能力,并且容量还比较大。
  2. jsStore只是众多封装的indexedDB库中的一个。可以用一种类似SQL的感觉操作数据

开始
package.json

{
  "name": "npm1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "lint": "eslint scripts/**",
    "fix": "eslint scripts/** --fix",
    "serve": "webpack serve"
  },
  "dependencies": {
    "jsstore": "^4.4.4",
    "lodash": "^4.17.21"
  },
  "devDependencies": {
    "css-loader": "^6.7.1",
    "eslint": "^8.23.1",
    "eslint-config-google": "^0.14.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-plugin-prettier": "^4.2.1",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.5.0",
    "prettier": "2.7.1",
    "style-loader": "^3.3.1",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.11.1"
  },
  "author": "",
  "license": "ISC"
}

webpack配置,添加了devServer配置

//webpack.config.js
 const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  context: path.resolve(__dirname),
  devServer: {
    static: {
      directory: path.join(__dirname, "dist"),
    },
    compress: true,
    port: 9000,
  },
  mode: "production",
  optimization: {
    minimize: false,
  },
  entry: "./src/main.js",
  target: ["web", "es5"],
  output: {
    clean: true,
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html",
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
};

jsStore链接帮助类,结合webpack+webworker。安装了file-loader

//store-connection.js
 import { Connection } from "jsstore";
const getWorkerPath = () => {
  // return dev build when env is development
  if (process.env.NODE_ENV === "development") {
    return require("file-loader?name=scripts/[name].[hash].js!jsstore/dist/jsstore.worker.js");
  } else {
    // return prod build when env is production

    return require("file-loader?name=scripts/[name].[hash].js!jsstore/dist/jsstore.worker.min.js");
  }
};

const workerPath = getWorkerPath().default;
export const connection = new Connection(new Worker(workerPath));

主逻辑

//main.js
 import { connection } from "./store-connection";

async function init() {
  var dbName = "JsStore_Demo";
  var tblProduct = {
    name: "Product",
    columns: {
      // Here "Id" is name of column
      id: { primaryKey: true, autoIncrement: true },
      itemName: { notNull: true, dataType: "string" },
      price: { notNull: true, dataType: "number" },
      quantity: { notNull: true, dataType: "number" },
    },
  };
  var database = {
    name: dbName,
    tables: [tblProduct],
  };

  const isDbCreated = await connection.initDb(database);
  if (isDbCreated === true) {
    console.log("db created");
    // here you can prefill database with some data
  } else {
    console.log("db opened");
  }

  var value = {
    itemName: "Blue Jeans",
    price: 2000,
    quantity: 1000,
  };

  var insertCount = await connection.insert({
    into: "Product",
    values: [value],
  });

  console.log(`${insertCount} rows inserted`);

  // results will be array of objects
  var results = await connection.select({
    from: "Product",
  });

  results.forEach((item) => {
    console.log(item);
  });
}

window.addEventListener("load", function () {
  console.log(connection);
  init();
});

数据已经存进去了

API插入、查询也没什么问题

总结

  1. 使用indexDB强化自己的demo体验,避免搭建后端环境,增加复杂度
  2. jsStore 的API多了解下,并且涉及的indexedDB的API都是异步的
  3. API没有啥,主要就是打开链接,事务,CRUD。语法参考下官网的例子即可

https://jsstore.net/tutorial/get-started/

原文链接:https://www.cnblogs.com/lee35/p/16736557.html