首页
休闲直播
4K壁纸
统计
关于
留言
更多
归档
Search
1
emby+alist3+cloudDriver2 emby无法播放网盘资源问题
376 阅读
2
关于服务器配置反代隐藏端口中遇到的问题
236 阅读
3
maptalks 一些基础api的再封装(待解耦改装纯方法类)
182 阅读
4
HelloWorld!
176 阅读
5
前端算法整理
169 阅读
生活
学习
随笔
吐槽
小秘密
小故事
登录
找到
77
篇与
相关的结果
- 第 2 页
2025-02-20
简单封装indexDB类
// indexDB.ts // 索引和游标分页查询数据类型 type SearchParamsType = { storeName: string, indexName: string, indexValue?: string | number | null, page: number, pageSize: number } // 仓库索引对象类型 type StoreListItem = { name: string, params: unknown } // 插入数据类型 type DataType = { [key: string]: unknown; } // 创建数据表参数类型 export interface StoreType { storeName: string, optionalParameters: { keyPath: string[] | string, autoIncrement?: boolean }, storeIndexList?: StoreListItem[] // 假设 storeList 是一个数组,可以根据实际情况更改类型 } export default class IndexDB<T extends (StoreType[] | StoreType)> { private dbName: string; private version: number; private IndexDB: IDBDatabase | undefined; isReady: boolean; constructor(dbName:string, version:number = 1) { this.IndexDB = void 0; // Initialize IndexDB this.dbName = dbName this.version = version this.isReady = false } // 打开数据库 /** * * @param store 初始化数据库表结构 * @returns db */ openDB(store: T){ return new Promise((resolve, reject) => { // this.store = store // 兼容浏览器 const dbObj = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB // 打开数据库,若没有则会创建 const request = dbObj.open(this.dbName, this.version) // 数据库打开成功回调 request.onsuccess = (event) => { this.IndexDB = (event.target as IDBOpenDBRequest).result console.log("数据库打开成功",this.IndexDB) resolve(true) // 数据库对象 } // 数据库打开失败的回调 request.onerror = (event) => { console.log("数据库打开失败",event) reject(null) } // 数据库有更新时候的回调 request.onupgradeneeded = (event) => { console.log("数据库有更新") const db = (event.target as IDBOpenDBRequest).result let objectStore: IDBObjectStore // 初始化存储库 if(this.version === 1){ // 如果多表格 if(Array.isArray(store)){ store.forEach(storeItem => { const { storeName, optionalParameters, storeIndexList } = storeItem objectStore = db.createObjectStore(storeName, optionalParameters) // 创建索引,在后面查询数据的时候可以根据索引查 storeIndexList?.forEach(item => { objectStore.createIndex(`${item.name}Index`, item.name, item.params) }) }) return } // 单表格 const { storeName, optionalParameters, storeIndexList } = store objectStore = db.createObjectStore(storeName, optionalParameters) // 创建索引,在后面查询数据的时候可以根据索引查 storeIndexList?.forEach(item => { objectStore.createIndex(`${item.name}Index`, item.name, item.params) }) } } }) } /** * 数据库创建完成 */ setReadyState(){ this.isReady = true } /** * 关闭数据库 */ closeDB(){ this.IndexDB?.close() console.log("数据库已关闭") } /** * 获取当前实例数据库 * @returns */ // getIndexDB(){ // return this.IndexDB // } /** * 数据插入 * @param storeName 仓库名 * @param data 插入数据 * @returns */ inert(storeName: string, data: DataType): Promise<boolean> { return new Promise((resolve, reject) => { const request = this.IndexDB?.transaction([storeName], "readwrite") // 事务对象 指定表格名称和操作模式("只读"或"读写") .objectStore(storeName) // 指定表格 .add(data) // 插入数据 if(request){ // 插入数据成功的回调 request.onsuccess = () => { // console.log("数据插入成功") resolve(true) } // 插入数据失败的回调 request.onerror = (event) => { console.log("数据插入失败", event) reject(false) } }else resolve(false) }) } /** * 数据根据主键查询 * @param storeName 仓库名 * @param key 主键值 */ queryByKeyr<U>(storeName: string, key: string | number): Promise<U | null> { return new Promise((resolve, reject) => { const request = this.IndexDB?.transaction([storeName]) // 事务对象 指定表格名称和操作模式("只读"或"读写") .objectStore(storeName) // 指定表格 .get(key) // 插入数据 if(request){ // 查询数据成功的回调 request.onsuccess = () => { // console.log("数据查询成功") resolve(request.result as U) } // 查询数据失败的回调 request.onerror = (event) => { console.log("queryByKey 查询失败", event) reject(null) } }else resolve(null) }) } /** * 通过游标读取所有数据 * @param storeName 仓库名 */ queryByCursor<U>(storeName: string): Promise<U[] | null> { return new Promise((resolve, reject) => { try{ const list: U[] = [] const request = this.IndexDB?.transaction([storeName], "readwrite") // 事务对象 指定表格名称和操作模式("只读"或"读写") .objectStore(storeName) // 指定表格 .openCursor() // 指针对象 if(request){ request.onsuccess = (event: Event) => { // 游标开启成功,逐行读数据 const cursor = (event.target as IDBRequest).result if(cursor){ list.push(cursor.value) cursor.continue() }else resolve(list) } }else resolve(null) }catch(err){ console.log("queryByCursor error", err) reject(null) } }) } /** * 通过游标读取最新数据 * @param storeName 仓库名 */ queryLatestByCursor<U>(storeName: string): Promise<U | null>{ return new Promise((resolve, reject) => { try{ const list: Record<string, U>[] = [] const request = this.IndexDB?.transaction([storeName], "readwrite") // 事务对象 指定表格名称和操作模式("只读"或"读写") .objectStore(storeName) // 指定表格 .openCursor() // 指针对象 if(request){ request.onsuccess = (event: Event) => { // 游标开启成功,逐行读数据 const cursor = (event.target as IDBRequest).result if(cursor){ list.push(cursor.value) cursor.continue() }else resolve(list.at(-1) as U) } }else resolve(null) }catch(err){ console.log("queryLatestByCursor error",err) reject(null) } }) } /** * 通过索引读取所有数据 * @param storeName * @param indexName * @param indexValue */ queryByIndex<U>(storeName: string, indexName: string, indexValue: string | number): Promise<U[] | null> { return new Promise((resolve, reject) => { const request = this.IndexDB?.transaction([storeName]) // 事务对象 指定表格名称和操作模式("只读"或"读写") .objectStore(storeName) // 指定表格 .index(indexName).get(indexValue) // 根据索引和索引值查询 if(request){ // 查询数据成功的回调 request.onsuccess = (event) => { // console.log("数据查询成功") resolve((event.target as IDBRequest).result as U[]) } // 查询数据失败的回调 request.onerror = (event) => { console.log("queryByIndex 查询失败", event) reject(null) } }else resolve(null) }) } /** * 通过索引和游标分页查询数据 * @param storeName * @param indexName * @param indexValue * @param page, * @param pageSize * @returns */ queryByIndexCursor<U>({ storeName, indexName, indexValue, page, pageSize }: SearchParamsType): Promise<U[] | null> { return new Promise((resolve, reject) => { try{ const list: U[] = [] let counter = 0 // 计数器 let advanced = true // 是否跳过多少条查询 const request = this.IndexDB?.transaction([storeName], "readonly") // 事务对象 指定表格名称和操作模式("只读") .objectStore(storeName) // 指定表格 .index(indexName) // 索引对象 .openCursor(indexValue ? IDBKeyRange.only(indexValue) : null) // 指针对象 if(request){ request.onsuccess = (event: Event) => { // 游标开启成功,逐行读数据 const cursor = (event.target as IDBRequest).result // 查询分页逻辑 if(page > 1 && advanced) { advanced = false cursor.advance((page - 1) * pageSize) return } if(cursor) { list.push(cursor.value) counter++ if(counter < pageSize) { cursor.continue() // 遍历了存储对象中的所有内容 }else{ resolve(list) } } } }else resolve(null) }catch(err){ console.log("queryByIndexCursor error", err) reject(null) } }) } /** * 更新数据 * @param storeName * @param data */ updated(storeName: string, data: DataType): Promise<boolean> { return new Promise((resolve, reject) => { const request = this.IndexDB?.transaction([storeName], "readwrite") // 事务对象 指定表格名称和操作模式("只读"或"读写") .objectStore(storeName) // 指定表格 .put(data) if(request){ // 查询数据成功的回调 request.onsuccess = () => { // console.log("数据更新成功") resolve(true) } // 查询数据失败的回调 request.onerror = (event) => { console.log("updated 更新失败",event) reject(event) } }else resolve(false) }) } /** * 更新数据 不存在创建 * @param storeName * @param data * data: Record<string, T> */ async upsert(storeName: string, data?: DataType): Promise<boolean> { try{ const list = await this.queryByCursor(storeName) // 新建 if(Array.isArray(list) && !list.length && data){ if(await this.inert(storeName, data)){ return true } } const res = Array.isArray(list) && list.at(-1) if(res && data){ await this.inert(storeName, data) return true } return false }catch(err){ console.log("upsert error", err) return false } } /** * 删除数据 * @param storeName * @param key */ delete(storeName: string, key: string | number): Promise<boolean> { return new Promise((resolve, reject) => { const request = this.IndexDB?.transaction([storeName], "readwrite") // 事务对象 指定表格名称和操作模式("只读"或"读写") .objectStore(storeName) // 指定表格 .delete(key) if(request){ // 查询数据成功的回调 request.onsuccess = () => { // console.log("数据删除成功") resolve(true) } // 查询数据失败的回调 request.onerror = (event) => { console.log("delete 删除失败",event) reject(event) } }else resolve(false) }) } }使用 import IndexDB,{ StoreType } from '@/utils/indexDB' async function createDB(): Promise<IndexDB<StoreType | StoreType[]> | null> { return new Promise(reslove => { const indexDB = new IndexDB('cache', 1) indexDB.openDB([ { storeName: 'cacheMicro', // 仓库名 optionalParameters: { keyPath: 'id', autoIncrement: true }, // 主键 keyPath可穿数组 storeIndexList:[ // 索引字段配置 { name: 'cacheMicroAppList', params:{ unique: false } } ] }, { storeName: 'cacheMicroNum', // 多个仓库创建 optionalParameters: { keyPath: 'id', autoIncrement: true }, }, ]).then(() => { if (indexDB) { reslove(indexDB) } else { throw new Error("Failed to get IndexDB instance"); } }) }) } await createDB()
学习
snowlove
1年前
0
22
0
2025-02-17
qiankun框架 react子应用搭建遇到的问题
import react from "@vitejs/plugin-react-swc" export default { ... plugins: [ // 本地调式时是不会报错的 但是当将该应用接入到乾坤中时 会报错(查看下面的图片) // 所以当接入乾坤时 需要去掉plugin-react插件 react(), AutoImport({ // target to transform include: [ /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx ], imports: [ 'react', // 'react-router-dom', // 'ahooks' ], dts: join(__dirname, 'src/types/auto-imports.d.ts'), // 生成到 types 目录下 resolvers: [AntdResolver()] }), legacy({ targets: ['defaults', 'not IE 11'], }), chunkSplitPlugin(), qiankun('micro', { useDevMode: true }), ] }报错信息如下 [import-html-entry]: error occurs while executing normal script <script type="module"> import RefreshRuntime from "/react-app/@react-refresh" RefreshRuntime.injectIntoGlobalHook(window) window.$RefreshReg$ = () => {} window.$RefreshSig$ = () => (type) => type window.__vite_plugin_react_preamble_installed__ = true </script>解决: const mode = process.env.NODE_ENV || 'development' ... plugins: [ mode === 'qiankun' || mode === 'production' ? '' : react() ]package.json "scripts": { "dev": "vite", "serve": "NODE_ENV=qiankun vite", "build": "NODE_ENV=production vite build", }
学习
snowlove
1年前
0
149
0
2025-02-10
消除异步传染
function getUser() { return fetch('https://my-json-server.typicode.com/typicode/demo/profile') } function m1() { // other works return getUser(); } function m2() { // other works return m1(); } function m3() { // other works return m2(); } function main(){ const res = m3() console.log("main",res) // main Promise { <pending> } } main() // 要求:在不改动以上方法的情况下 如何避免使用async await方法 将所有方法都传染为同步方法 且控制台输出请求结果 // 一种方法 /** * function main(){ m3().then(res=>{console.log("main",res)}) // {"name": "typicode"} } */ // 另一种方法 function run(func){ const _originWindowFetch = globalThis.fetch const cache = new Map() // 1.第一次请求直接报错 // 2.当接口请求成功后,缓存结果,在下次同意请求时将缓存结果返回 globalThis.fetch = (...args) => { const url = args[0] const fetchStatus = { requestId: url, status: 'pending', // pending; fulfilled; rejected data: null, err: null, } let cacheFetch = cache.get(url) // 此处判断是否有缓存 if(cacheFetch){ if(cacheFetch.status === 'fulfilled'){ // 移除 cache.delete(url) return cacheFetch.data } if(cacheFetch.status === 'rejected'){ // 移除 cache.delete(url) throw cacheFetch.err } } cacheFetch = cache.set(url,fetchStatus).get(url) // 首次请求获得缓存返回值 const promise = _originWindowFetch(args).then((resp) => resp.json()) .then(res=>{ cacheFetch.status = 'fulfilled' cacheFetch.data = res },err=>{ cacheFetch.status = 'rejected' cacheFetch.err = err }) .catch((err) => { cacheFetch.status = 'rejected' cacheFetch.err = err }) throw promise } try { func() } catch (error) { if(error instanceof Promise){ const runFun = ()=>{ func() } // 重新执行 此处已经获取到请求结果 error.then(runFun,runFun).catch(runFun) } } } run(main)
学习
snowlove
1年前
0
33
0
2024-11-08
python class基础回顾
58d195fb49d72fe048108aa5fdf62405dc1fc359.jpg图片 class Test(object): '''类属性''' count = 0 def __init__(self,prefix): self._prefix = prefix Test.count += 1 '''直接通过类名来调用的方法叫做类方法也叫静态方法 ,不需要先创建实例,可以定义成这个类的静态属性,通过关键字@staticmethod来标记。''' @staticmethod def version(): return "1.0" '''使用 @property 可以为类定义一个只读属性。这种属性只会有一个 getter 方法,而没有 setter 方法,从而禁止修改该属性的值。''' @classmethod def getSubClass(cls, prefix): return cls(prefix) '''获取类属性 基数当前一共生成了多少个子类''' @classmethod def getCount(cls): return cls.count @property def prefix(self): return self._prefix '''可以通过 @property 和 @<property_name>.setter 组合来定义可读写属性。在 setter 中可以加入条件检查或其他逻辑,确保属性符合要求''' @prefix.setter def prefix(self, value): self._prefix = value '''@property 可以将一个方法定义为计算属性,通过一定的逻辑计算返回一个值,而不需要存储该值。''' def console(self, content): print(f"{self._prefix} : {content}") test = Test('Hello World 1') test.console(2) test.prefix = 'Hello World 3' print('哈哈哈',test.prefix) test.console(4) print(Test.version()) # 使用静态方法直接获取一个新的子类 test2 = Test.getSubClass('我是一个Test子类') test2.console('Hello World 5') print(Test.getCount()) class Test_Sub(Test): def __init__(self, prefix): super().__init__(prefix) def sub_function(self): return f"{self._prefix}: sub function" test_sub = Test_Sub.getSubClass('我是一个继承Test的Test_Sub子类') print('哈哈哈',test_sub.prefix) print(Test_Sub.getCount()) ''' Hello World 1 : 2 Hello World 3 : 4 1.0 我是一个Test子类 : Hello World 5 2 我是一个继承Test的Test_Sub子类 3 ''' # 此处并没有打印 print(test_sub.prefix) Test_Sub不是继承自Test 那么test_sub实例应该有prefix? ''' 解释: Test_Sub 的构造函数(__init__)缺失 修改: class Test_Sub(Test): def __init__(self, prefix): super().__init__(prefix) # 调用父类的构造函数,初始化 prefix def sub_function(self): return f"{self._prefix}: sub function" '''
学习
snowlove
2年前
0
31
0
2024-11-08
nginx相关知识点
v2-7aac9ef2a6fe63d71971adfa7ff7695b_720w.png图片 b3f686be-1dce-4749-a5ac-a79825232095.jpeg图片 在 Nginx 配置文件中,root 和 alias 都用于指定文件系统中的路径,以便在处理请求时找到相应的资源 1.root 和 alias 的区别 /var/www/html ├── index.html ├── images │ └── pic.jpg └── static └── app.js我们要将 /var/www/html 目录作为网站的根目录,并处理以下两种情况: / 请求时返回 index.html 。 /images/ 请求时返回 /var/www/html/images/ 下的文件。 root 示例: server { listen 80; server_name example.com; # 根路径 location / { root /var/www/html; # 将会找到 /var/www/html/index.html } # images 文件夹 location /images/ { root /var/www/html; # 请求 /images/pic.jpg 时,Nginx 将去查找 /var/www/html/images/pic.jpg } }alias 示例: server { listen 80; server_name example.com; # 根路径 location / { root /var/www/html; } # images 文件夹 location /images/ { alias /var/www/html/images/; # 请求 /images/pic.jpg 时,Nginx 会直接查找 /var/www/html/images/pic.jpg } }2.流量镜像功能 之前做过日志收集的系统 使用的方案是发送请求时同步调用日志服务器的数据数据收集接口 等于一次请求要发送两次的http请求 如果采用镜像可能会更优雅些 示例: location / { mirror /mirror; proxy_pass http://backend; } location = /mirror { internal; # 路径只能被 Nginx 内部请求访问 proxy_pass http://test_backend$request_uri; }3. Nginx常用的内置变量 859b3c4316231213ccd070308dd5dd98.jpeg图片 4. Nginx location 匹配规则 路径匹配,优先级:(跟 location 的书写顺序关系不大) 精确匹配 : =前缀的指令严格匹配这个查询。 如果找到,停止搜索。 普通字符匹配 : 所有剩下的常规字符串,最长的匹配。 如果这个匹配使用^〜前缀,搜索停止。 正则匹配 : 正则表达式,在配置文件中定义的顺序,匹配到一个结果,搜索停止; 默认匹配 : 如果第3条规则产生匹配的话,结果被使用。 否则,如同从第2条规则被使用。 示例: location = /exact { ... } # 精准匹配 location ^~ /images/ { ... } # 通配前缀匹配 location /images/pictures/ { ... } # 普通前缀匹配 location / { ... } # 默认前缀匹配 location ~ \.jpg$ { ... } # 区分大小写的正则匹配 location ~* \.png$ { ... } # 不区分大小写的正则匹配 请求 /exact:匹配 location = /exact,因为它是精准匹配。 请求 /images/abc.jpg:匹配 location ^~ /images/,因为通配前缀匹配优先于正则。 请求 /images/pictures/123.jpg:匹配 location /images/pictures/,因为它是最长的普通前缀匹配。 请求 /test.jpg:匹配 location ~ .jpg$,因为它符合正则匹配。 请求 /test.png:匹配 location ~* .png$,因为它符合不区分大小写的正则匹配。 请求 /other:匹配 location /,因为它是最后的通用匹配。 未完待续... 参考: 民工哥技术之路 nginx在同一域名下部署多个vue项目
学习
snowlove
2年前
0
35
0
上一页
1
2
3
...
16
下一页