· 5 years ago · Mar 06, 2021, 08:40 PM
1import { ISessionStorage } from '@vk-io/session'
2import serialize from 'serialize-javascript'
3import { API, VK } from 'vk-io'
4
5/**
6 * TODO: Add TTL
7 * https://github.com/negezor/vk-io/issues/380
8 */
9export class VkStorage implements ISessionStorage {
10 private api: API
11
12 constructor(vk: VK) {
13 this.api = vk.api
14 }
15
16 public async get(key: string): Promise<object | undefined> {
17 const [storage] = await this.api.storage.get({ key, user_id: Number(key) })
18
19 return this.deserialize(storage.value)
20 }
21
22 public async set(key: string, value: object): Promise<boolean> {
23 return Boolean(
24 await this.api.storage.set({
25 key,
26 value: serialize(value),
27 user_id: Number(key),
28 }),
29 )
30 }
31
32 public async delete(key: string): Promise<boolean> {
33 return Boolean(
34 await this.api.storage.set({ key, value: null, user_id: Number(key) }),
35 )
36 }
37
38 // eslint-disable-next-line class-methods-use-this
39 public async touch(): Promise<void> {
40 // ...
41 }
42
43 private deserialize(serializedJavascript: string) {
44 console.log(serializedJavascript)
45
46 return eval('(' + serializedJavascript + ')')
47 }
48}
49