mirror of
https://github.com/FranP-code/Baileys.git
synced 2025-10-13 00:32:22 +00:00
feat: implement in memory store
1. the store works as a temporary store for connection data such as chats, messages & contacts 2. the store is primarily meant to illustrate the usage of the event emitter as a way to construct the state of the connection. This will likely be very inefficient to perform well at scale 3. the store is meant to be a quick way to have some visibility of data while testing 4. the store works for both legacy & MD connections
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
function makeOrderedDictionary<T>(idGetter: (item: T) => string) {
|
||||
const array: T[] = []
|
||||
const dict: { [_: string]: T } = { }
|
||||
|
||||
const get = (id: string) => dict[id]
|
||||
|
||||
const update = (item: T) => {
|
||||
const id = idGetter(item)
|
||||
const idx = array.findIndex(i => idGetter(i) === id)
|
||||
if(idx >= 0) {
|
||||
array[idx] = item
|
||||
dict[id] = item
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
const upsert = (item: T, mode: 'append' | 'prepend') => {
|
||||
const id = idGetter(item)
|
||||
if(get(id)) {
|
||||
update(item)
|
||||
} else {
|
||||
if(mode === 'append') {
|
||||
array.push(item)
|
||||
} else {
|
||||
array.splice(0, 0, item)
|
||||
}
|
||||
|
||||
dict[id] = item
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (item: T) => {
|
||||
const id = idGetter(item)
|
||||
const idx = array.findIndex(i => idGetter(i) === id)
|
||||
if(idx >= 0) {
|
||||
array.splice(idx, 1)
|
||||
delete dict[id]
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return {
|
||||
array,
|
||||
get,
|
||||
upsert,
|
||||
update,
|
||||
remove,
|
||||
updateAssign: (id: string, update: Partial<T>) => {
|
||||
const item = get(id)
|
||||
if(item) {
|
||||
Object.assign(item, update)
|
||||
delete dict[id]
|
||||
dict[idGetter(item)] = item
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
clear: () => {
|
||||
array.splice(0, array.length)
|
||||
Object.keys(dict).forEach(key => {
|
||||
delete dict[key]
|
||||
})
|
||||
},
|
||||
filter: (contain: (item: T) => boolean) => {
|
||||
let i = 0
|
||||
while(i < array.length) {
|
||||
if(!contain(array[i])) {
|
||||
delete dict[idGetter(array[i])]
|
||||
array.splice(i, 1)
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
},
|
||||
toJSON: () => array,
|
||||
fromJSON: (newItems: T[]) => {
|
||||
array.splice(0, array.length, ...newItems)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default makeOrderedDictionary
|
||||
Reference in New Issue
Block a user