├── .eslintrc ├── .gitignore ├── .umirc.library.js ├── LICENSE ├── README.md ├── package.json ├── src ├── index.ts └── type.ts └── tsconfig.json /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "eslint-config-umi", 3 | "rules": { 4 | "indent": ["error", 2], 5 | "linebreak-style": ["error", "unix"], 6 | "quotes": ["error", "single"], 7 | "semi": ["warn", "never"], 8 | "no-constant-condition": "warn", 9 | "no-dupe-args": "warn", 10 | "no-extra-semi": "warn", 11 | "default-case": "warn", 12 | "eqeqeq": "warn", 13 | "no-alert": "warn", 14 | "no-empty-function": "warn", 15 | "arrow-spacing": "warn", 16 | "no-unused-vars": "warn", 17 | "comma-dangle": "warn", 18 | "curly": "warn", 19 | "no-eval": "warn", 20 | "no-extra-label": "warn", 21 | "no-multi-spaces": "warn", 22 | "no-redeclare": "warn", 23 | "no-unused-expressions": "warn", 24 | "no-with": "warn", 25 | "radix": "warn", 26 | "max-lines": [ "error", {"max": 400, "skipComments": true }] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /.umirc.library.js: -------------------------------------------------------------------------------- 1 | export default { 2 | entry: 'src/index.ts', 3 | doc: { 4 | title: 'xdbjs', 5 | themeConfig: { mode: 'light' }, 6 | }, 7 | autoprefixer: { 8 | browsers: [ 9 | 'ie>10' 10 | ], 11 | }, 12 | runtimeHelpers: true, 13 | esm: { 14 | type: 'rollup', 15 | file: 'xdb.esm' 16 | }, 17 | cjs: { 18 | type: 'rollup', 19 | file: 'xdb.cjs' 20 | }, 21 | umd: { 22 | file: 'xdb.umd', 23 | minFile: true 24 | }, 25 | target: "browser" 26 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 MrXujiang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # xdb 2 | 基于indexedDB API二次封装的支持过期时间,且采用promise封装的存储库 3 | 4 | # 使用 5 | ### 1.初始化数据库 6 | ``` js 7 | // 连接indexedDB数据库并创建表 8 | var tableName = 'cacheTable' 9 | window.db = xdb.loadDB({ 10 | name: 'cacheDB', 11 | onUpdate(e) { 12 | console.log('update', e) 13 | db.createTable(tableName, { keyPath: 'path'}) 14 | }, 15 | onSuccess(e) { 16 | console.log('success', e) 17 | } 18 | }) 19 | ``` 20 | ### 2.获取表中的数据 21 | ``` js 22 | db.get(tableName, 'keypath').then(res => {}) 23 | // 或者在async函数中 24 | const res = await db.get(tableName, 'keypath') 25 | ``` 26 | ### 3.添加table行数据 27 | ``` js 28 | // 第三个参数为过期时间 29 | db.add(tableName, data, 24 * 60 * 60 * 1000) 30 | ``` 31 | 32 | ### 4. 删除数据 33 | ``` js 34 | db.del(tableName, keyVal) 35 | ``` 36 | 37 | ### 5. 清空table 38 | ``` js 39 | db.clear() 40 | ``` 41 | 42 | ### 6.更新行 43 | ``` js 44 | db.update(tableName, data) 45 | ``` 46 | 47 | ### 更多产品推荐 | More Production 48 | 49 | | name | Description | 50 | | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | 51 | | [H5-Dooring](https://github.com/MrXujiang/h5-Dooring) | 让 H5 制作像搭积木一样简单, 轻松搭建 H5 页面, H5 网站, PC 端网站, LowCode 平台. | 52 | | [V6.Dooring](https://github.com/MrXujiang/v6.dooring.public) | 可视化大屏解决方案, 提供一套可视化编辑引擎, 助力个人或企业轻松定制自己的可视化大屏应用. | 53 | | [dooring-electron-lowcode](https://github.com/MrXujiang/dooring-electron-lowcode) | 基于 electron 的 H5-Dooring 编辑器桌面端. | 54 | | [xijs](https://github.com/MrXujiang/xijs) | 开箱即用的js业务工具库 | 55 | | [DooringX](https://github.com/H5-Dooring/dooringx) | 快速高效搭建可视化拖拽平台. | 56 | 57 | ## 赞助 | Sponsored 58 | 59 | 开源不易, 有了您的赞助, 我们会做的更好~ 60 | 61 | 62 | 63 | ## 技术反馈和交流群 | Technical feedback and communication 64 | 65 | 微信:beautifulFront 66 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@alex_xu/xdb", 3 | "version": "0.1.0-snapshot.41", 4 | "description": "基于indexedDB的前端缓存库", 5 | "main": "dist/xdb.cjs.js", 6 | "module": "dist/xdb.esm.js", 7 | "browser": "dist/xdb.umd.js", 8 | "author": "alex_xu", 9 | "homepage": "", 10 | "keywords": [ 11 | "tools", 12 | "javascript", 13 | "library", 14 | "general" 15 | ], 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/MrXujiang/dao.js.git" 19 | }, 20 | "dependencies": { 21 | "@babel/runtime": "^7.6.3", 22 | "querystring": "^0.2.0", 23 | "umi-library": "^1.6.0" 24 | }, 25 | "scripts": { 26 | "dev": "umi-lib doc dev", 27 | "build": "umi-lib build", 28 | "build:doc": "umi-lib doc build", 29 | "test": "echo \"Error: no test specified\" && exit 1" 30 | }, 31 | "files": [ 32 | "dist" 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | declare global { 2 | interface Window { xdb: any; } 3 | } 4 | 5 | const xdb = (() => { 6 | let instance:any = null 7 | let dbName = '' 8 | let DB = function(args:any) { 9 | const cfg = { 10 | name: args.name || 'test', 11 | version: args.version || 1, 12 | onSuccess(e:Event) { 13 | args.onSuccess && args.onSuccess(e) 14 | }, 15 | onUpdate(e:Event) { 16 | args.onUpdate && args.onUpdate(e) 17 | }, 18 | onError(e:Event) { 19 | args.onError && args.onError(e) 20 | } 21 | } 22 | this.dbName = args.name 23 | this.request = null 24 | this.db = null 25 | // 打开/创建数据库 26 | this.init = function() { 27 | if (!window.indexedDB) { 28 | console.log('你的浏览器不支持该版本') 29 | return 30 | } 31 | 32 | let _this = this 33 | 34 | this.request = window.indexedDB.open(this.dbName, cfg.version) 35 | this.request.onerror = function (event:Event) { 36 | cfg.onError(event) 37 | } 38 | 39 | 40 | this.request.onsuccess = function (event:Event) { 41 | _this.db = _this.request.result 42 | cfg.onSuccess(event) 43 | } 44 | 45 | this.request.onupgradeneeded = function (event:any) { 46 | _this.db = event.target.result 47 | cfg.onUpdate(event) 48 | } 49 | } 50 | 51 | this.init() 52 | 53 | // 添加表 54 | this.createTable = function(name:string, opts:any = {}) { 55 | let objectStore:any 56 | if (!this.db.objectStoreNames.contains(name)) { 57 | opts = { 58 | keyPath: opts.keyPath, 59 | indexs: Array.isArray(opts.indexs) ? opts.indexs : [] 60 | } 61 | 62 | // indexs = [{ 63 | // indexName: 'name', 64 | // key: 'name', 65 | // unique: true 66 | // }] 67 | 68 | objectStore = this.db.createObjectStore(name, { keyPath: opts.keyPath }) 69 | 70 | if(opts.length) { 71 | opts.indexs.forEach((item:any) => { 72 | objectStore.createIndex(item.indexName, item.key, { unique: item.unique }) 73 | }) 74 | } 75 | return objectStore 76 | } 77 | } 78 | 79 | // 访问表中数据 80 | this.get = function(tableName:string, keyPathVal:any) { 81 | let _this = this 82 | return new Promise((resolve, reject) => { 83 | let transaction = this.db.transaction([tableName]) 84 | let objectStore = transaction.objectStore(tableName) 85 | let request = objectStore.get(keyPathVal) 86 | 87 | request.onerror = function(event:Event) { 88 | reject({status: 500, msg: '事务失败', err: event}) 89 | } 90 | 91 | request.onsuccess = function(event:Event) { 92 | if (request.result) { 93 | // 判断缓存是否过期 94 | if(request.result.ex < Date.now()) { 95 | resolve({status: 200, data: null}) 96 | _this.del(tableName, keyPathVal) 97 | }else { 98 | resolve({status: 200, data: request.result}) 99 | } 100 | } else { 101 | resolve({status: 200, data: null}) 102 | } 103 | } 104 | }) 105 | } 106 | 107 | // 遍历访问表中所有数据 108 | this.getAll = function(tableName:string) { 109 | return new Promise((reslove, reject) => { 110 | let objectStore = this.db.transaction(tableName).objectStore(tableName) 111 | let result:any = [] 112 | objectStore.openCursor().onsuccess = function (event:any) { 113 | let cursor = event.target.result 114 | 115 | if (cursor) { 116 | result.push(cursor.value) 117 | cursor.continue() 118 | } else { 119 | reslove({status: 200, data: result}) 120 | } 121 | } 122 | 123 | objectStore.openCursor().onerror = function (event:Event) { 124 | reject({status: 500, msg: '事务失败', err: event}) 125 | } 126 | }) 127 | } 128 | 129 | // 从表中添加一条数据 130 | this.add = function(tableName:string, row:any, ex:number) { 131 | return new Promise((reslove, reject) => { 132 | let request = this.db.transaction([tableName], 'readwrite') 133 | .objectStore(tableName) 134 | .add(Object.assign(row, ex ? { ex: Date.now() + ex } : {})) 135 | 136 | request.onsuccess = function (event:Event) { 137 | reslove({status: 200, msg: '数据写入成功'}) 138 | } 139 | 140 | request.onerror = function (event:Event) { 141 | reject({status: 500, msg: '数据写入失败', err: event}) 142 | } 143 | }) 144 | 145 | } 146 | 147 | // 更新表中的数据 148 | this.update = function(tableName:string, row:any) { 149 | return new Promise((reslove, reject) => { 150 | let request = this.db.transaction([tableName], 'readwrite') 151 | .objectStore(tableName) 152 | .put(row) 153 | 154 | request.onsuccess = function (event:Event) { 155 | reslove({status: 200, msg: '数据更新成功'}) 156 | } 157 | 158 | request.onerror = function (event:Event) { 159 | reject({status: 500, msg: '数据更新失败', err: event}) 160 | } 161 | }) 162 | } 163 | 164 | // 删除某条数据 165 | this.del = function(tableName:string, keyPathVal:any) { 166 | return new Promise((resolve, reject) => { 167 | let request = this.db.transaction([tableName], 'readwrite') 168 | .objectStore(tableName) 169 | .delete(keyPathVal) 170 | 171 | request.onsuccess = function (event:Event) { 172 | resolve({status: 200, msg: '数据删除成功'}) 173 | } 174 | 175 | request.onerror = function (event:Event) { 176 | reject({status: 500, msg: '数据删除失败', err: event}) 177 | } 178 | }) 179 | } 180 | 181 | // 清空表数据 182 | this.clear = function(tableName:string) { 183 | return new Promise((resolve, reject) => { 184 | let request = this.db.transaction([tableName], 'readwrite') 185 | .objectStore(tableName) 186 | .clear() 187 | 188 | request.onsuccess = function (event:Event) { 189 | resolve({status: 200, msg: '数据表已清空'}) 190 | } 191 | 192 | request.onerror = function (event:Event) { 193 | reject({status: 500, msg: '数据表清空失败', err: event}) 194 | } 195 | }) 196 | } 197 | } 198 | 199 | return { 200 | loadDB(args:any) { 201 | if(instance === undefined || dbName !== args.name) { 202 | instance = new (DB as any)(args) 203 | } 204 | return instance 205 | } 206 | } 207 | 208 | })() 209 | 210 | window.xdb = xdb 211 | 212 | export default xdb -------------------------------------------------------------------------------- /src/type.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MrXujiang/xdb/3602138c046959754561546c395da9a78fc5ff44/src/type.ts -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "esnext", 4 | "module": "esnext", 5 | "moduleResolution": "node", 6 | "importHelpers": true, 7 | "jsx": "react", 8 | "esModuleInterop": true, 9 | "sourceMap": true, 10 | "baseUrl": ".", 11 | "strict": true, 12 | "paths": { 13 | "@/*": ["src/*"] 14 | }, 15 | "allowSyntheticDefaultImports": true, 16 | "noImplicitThis": false 17 | } 18 | } 19 | --------------------------------------------------------------------------------