使用indexedDB,降低环境搭建成本

更新日期: 2022-09-28阅读: 758标签: IndexedDB

背景

  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://www.cnblogs.com/lee35/archive/2022/09/28/16736557.html

链接: https://www.fly63.com/article/detial/12180

indexedDB 数据库_html5中Web离线数据库的使用

HTML5的本地存储中有一种叫 indexedDB 的数据库,该数据库是一种存储在客户端本地的 NoSQL 数据库,它可以存储大量的数据。这篇文章讲解indexedDB 如何存储数据?

使用IndexedDB做前端日志持久化

页面如果表现不符合预期,前端工程师在没有 javascript 日志的情况下,很难 debug。所以就需要针对必要的步骤记录日志,并上传。但是每记录一条日志就上传并不是一个合适的选择

前端数据库:WebSQL和IndexedDB

WebSQL是前端的一个独立模块,是web存储方式的一种,我们调试的时候会经常看到,只是一般很少使用。兼容性:当前只有谷歌支持,ie和火狐均不支持。

IndexedDB:浏览器里的本地数据库

在现代浏览器的本地存储方案中,indexedDB 是一项重要的能力组成, 它是可以在浏览器端使用的本地数据库,可以存储大量数据,提供接口来查询,还可以建立索引,这些都是其他存储方案 Cookie 或者 LocalStorage 无法提供的能力

IndexedDB的使用

随着浏览器功能增强,许多网站开始将大量数据保存在客户端,从而减少从服务器获取数据的操作,提高了响应速度。cookie 由于大小不超过 4kb,肯定不合适。LocalStorage 大小在 2.5 - 10 M间

浏览器数据库 indexedDB

indexedDB用于在浏览器端存储大量的结构化数据。对比于其他的浏览器存储技术(cookie,localStorage),indexedDB具有以下优点:另外,indexedDB还具备以下特点:

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!