127.0.0.1:8000 watch-together / master src / js / utils / api.js
master

Tree @master (Download .tar.gz)

api.js @masterraw · history · blame

/* global grecaptcha */

const axios = require('axios');
const utils = require('.');
const ui = require('../ui/common');
const STATUS_CODES = Object.assign({
    video: require('../../../video_status.json')
}, require('../../../status.json'));

const get_captcha_token = process.env.NODE_ENV === 'production' ? function(data) {
    return new Promise(function(resolve) {
        grecaptcha.ready(function() {
            grecaptcha.execute('6LfNZvsUAAAAADGihvl9M1g0ypKt_qQBOYSd8slF', Object.assign({
                action: 'submit'
            }, data || {})).then(resolve);
        });
    });
} : () => utils.resolve("debug-captcha-token")

module.exports = {
    status: STATUS_CODES,
    post: function(path, data, options) {
        options = Object.assign({
            acceptable_status_codes: []
        }, options || {});
        options.acceptable_status_codes.push(STATUS_CODES.ok);
        return (
            options.add_captcha_token ?
            get_captcha_token(options.add_captcha_token).then(function(token) {
                return Object.assign(data, {
                    captcha_token: token
                });
            }) : utils.resolve(data)
        ).then(function(data) {
            console.log("POST to /api/" + path, "with options", options);
            return axios.post(`/api${path}`, data).catch(function(axios_error) {
                logger.error(axios_error);
                return utils.reject({
                    message: axios_error.response.data || "Server Error",
                    color: "red"
                });
            }).then(function(response) {
                console.log(response.data);
                if (options.acceptable_status_codes.includes(response.data.status)) {
                    return utils.resolve(response.data);
                }
                return utils.reject(response.data);
            });
        });
    },
    handle_error_message: function(error) {
        if (typeof error === "string") {
            ui.show_banner({
                message: error,
                color: "red"
            });
        } else {
            ui.show_banner(error);
        }
    }
};