summaryrefslogtreecommitdiff
path: root/cookies-storage.js
blob: 8c9231b47d0a6531c41c9c0eb5078dd0aacd8a69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const fs = require('fs').promises

let storageFileName = null

async function exists(path) {
    try {
        await fs.access(path)
        return true
    } catch {
        return false
    }
}

module.exports = {
    async save(newCookies) {
        let currentCookies = await this.get()
        if (currentCookies.length) {
            for (let newCookie of newCookies) {
                if (!currentCookies.length)
                    break
                let i = currentCookies.findIndex((c) => {
                    return c.domain === newCookie.domain
                        && c.path === newCookie.path
                        && c.name === newCookie.name
                })
                if (i !== -1)
                    currentCookies.splice(i, 1)
            }
        }
        currentCookies.push(...newCookies)
        // console.log('[cookies.save] saving cookies:', currentCookies)
        await fs.writeFile(storageFileName, JSON.stringify(currentCookies, null, 2), 'utf-8')
    },

    async get() {
        if (!(await exists(storageFileName)))
            return []

        try {
            return JSON.parse(await fs.readFile(storageFileName, 'utf-8'))
        } catch (e) {
            console.error(e)
            return []
        }
    },

    setFileName(name) {
        storageFileName = name
    }
};