All files / src BotConfigStorage.js

91.3% Statements 42/46
69.23% Branches 9/13
100% Functions 9/9
91.3% Lines 42/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171    1x 1x   1x                           2x                 3x 3x   3x           3x                   1x 1x 1x   2x 1x   1x 1x 1x                     2x 2x   2x                   2x 2x   2x       2x   2x                 3x   3x 3x   3x   3x   1x 1x                                       3x               2x 2x   2x       2x               2x 1x 1x       1x           1x           1x  
'use strict';
 
const mssql = require('mssql');
const { apiAuthorizer } = require('wingbot');
 
const CONFIG_ID = 'config';
 
/**
 * Storage for wingbot.ai conversation config
 *
 * @class
 */
class BotConfigStorage {
 
    /**
     *
     * @param {Promise<mssql.ConnectionPool>} pool
     */
    constructor (pool) {
        this._pool = pool;
    }
 
    /**
     * @param {object} newConfig
     */
 
    async _simpleUpdate (newConfig) {
 
        const cp = await this._pool;
        const r = cp.request();
 
        const res = await r
            .input('CONFIG_ID', mssql.VarChar, CONFIG_ID)
            .input('blocks', mssql.Text, Buffer.from(JSON.stringify(newConfig.blocks)).toString('base64'))
            .input('timestamp', mssql.BigInt, newConfig.timestamp)
            .query('UPDATE botConfigStorage SET timestamp = @timestamp, blocks = @blocks WHERE id = @CONFIG_ID');
 
        return res.rowsAffected[0] === 1;
    }
 
    /**
     * Returns botUpdate API for wingbot
     *
     * @param {Function} [onUpdate] - async update handler function
     * @param {Function|string[]} [acl] - acl configuration
     * @returns {{updateBot:Function}}
     */
    api (onUpdate = () => Promise.resolve(), acl) {
        const storage = this;
        return {
            async updateBot (args, ctx) {
                if (!apiAuthorizer(args, ctx, acl)) {
                    return null;
                }
                await storage.invalidateConfig();
                await onUpdate();
                return true;
            }
        };
    }
 
    /**
     * Invalidates current configuration
     *
     * @returns {Promise}
     */
    async invalidateConfig () {
        const cp = await this._pool;
        const r = cp.request();
 
        return r
            .input('CONFIG_ID', mssql.VarChar, CONFIG_ID)
            .query('DELETE FROM botConfigStorage WHERE botConfigStorage.id=@CONFIG_ID');
    }
 
    /**
     * @returns {Promise<number>}
     */
    async getConfigTimestamp () {
 
        const cp = await this._pool;
        const r = cp.request();
 
        const { recordset } = await r
            .input('CONFIG_ID', mssql.VarChar, CONFIG_ID)
            .query('SELECT timestamp FROM botConfigStorage WHERE botConfigStorage.id=@CONFIG_ID');
 
        const [res] = recordset;
 
        return res ? Number(res.timestamp) : 0;
    }
 
    /**
     * @template T
     * @param {T} newConfig
     * @returns {Promise<T>}
     */
    async updateConfig (newConfig) {
        Object.assign(newConfig, { timestamp: Date.now() });
 
        const cp = await this._pool;
        const r = cp.request();
 
        const up = await this._simpleUpdate(newConfig);
 
        if (!up) {
 
            try {
                await r
                    .input('CONFIG_ID', mssql.VarChar, CONFIG_ID)
                    // @ts-ignore
                    .input('blocks', mssql.Text, Buffer.from(JSON.stringify(newConfig.blocks)).toString('base64'))
                    // @ts-ignore
                    .input('timestamp', mssql.BigInt, newConfig.timestamp)
                    .query('INSERT INTO botConfigStorage (id, blocks, timestamp) VALUES (@CONFIG_ID, @blocks, @timestamp);');
 
            } catch (e) {
                // 2627 is unique constraint (includes primary key), 2601 is unique index
                if (e.number === 2601 || e.number === 2627) {
                    await this._simpleUpdate(newConfig);
                } else {
 
                    throw e;
                }
            }
 
        }
 
        return newConfig;
    }
 
    /**
     * @returns {Promise<object|null>}
     */
    async getConfig () {
 
        const cp = await this._pool;
        const r = cp.request();
 
        const { recordset } = await r
            .input('CONFIG_ID', mssql.VarChar, CONFIG_ID)
            .query('SELECT blocks, timestamp FROM botConfigStorage WHERE botConfigStorage.id=@CONFIG_ID');
 
        const [res] = recordset;
 
        // if (res) {
        //     const q = res.blocks.substring(1520, 1590);
 
        //     console.log(q);
        // }
 
        if (res) {
            try {
                const ret = {
                    blocks: JSON.parse(Buffer.from(res.blocks, 'base64').toString('utf8')),
                    timestamp: Number(res.timestamp)
                };
                return ret;
            } catch (e) {
                return null;
            }
        }
 
        return null;
 
    }
 
}
 
module.exports = BotConfigStorage;