Skip to content

Commit

Permalink
fix: 数据库删除数据bug
Browse files Browse the repository at this point in the history
  • Loading branch information
lc-cn committed Jul 11, 2024
1 parent 996f061 commit 4b49f41
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
8 changes: 6 additions & 2 deletions zhin/src/plugins/database/adapters/level.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,14 @@ export class LevelDb extends Level implements Database {
await this.set(key, data);
}
async remove<T>(key: string, predicate: Database.Predicate<T[]> | T): Promise<void> {
if (typeof predicate !== 'function') predicate = (item: T) => JSON.stringify(item) === JSON.stringify(predicate);
const data = await this.get<T[]>(key, [] as T[]);
if (!Array.isArray(data)) throw new Error(`${key} is not an array`);
await this.set(key, (data as any).filter(predicate));
const needRemoveData = data.filter((item, idx, list) => {
if (typeof predicate === 'function') return (predicate as Database.Predicate<T[]>)(item, idx, list);
return JSON.stringify(item) === JSON.stringify(predicate);
});
const newData = (data as any).filter((item: T) => !needRemoveData.includes(item));
await this.set(key, newData);
}
push<T>(key: string, ...value: T[]): Promise<void> {
return this.get(key, [] as T).then(data => {
Expand Down
12 changes: 7 additions & 5 deletions zhin/src/plugins/database/adapters/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,14 @@ export class RedisDb implements Database {
return true;
}
async remove<T>(key: string, predicate: T | Database.Predicate<T[]>): Promise<void> {
const data = await this.#getArray<T>(key);
const data = await this.get<T[]>(key, [] as T[]);
if (!Array.isArray(data)) throw new Error(`${key} is not an array`);
const index = typeof predicate === 'function' ? data.findIndex(predicate as any) : data.indexOf(predicate);
if (index === -1) return;
data.splice(index, 1);
await this.set(key, data);
const needRemoveData = data.filter((item, idx, list) => {
if (typeof predicate === 'function') return (predicate as Database.Predicate<T[]>)(item, idx, list);
return JSON.stringify(item) === JSON.stringify(predicate);
});
const newData = (data as any).filter((item: T) => !needRemoveData.includes(item));
await this.set(key, newData);
}
async start(): Promise<void> {
const client = this.client;
Expand Down

0 comments on commit 4b49f41

Please sign in to comment.