釘釘小程式 請求封裝

TheresaGU發表於2020-09-23
// network.js
function factory() {
    let res = dd.getStorageSync({ key: 'token' });
    let token = res.data.token;

    let Options = {
        host: '',
    };

    let Response = function (status, headers, data, content) {
        this.status = status || 0;
        this.headers = headers || {};
        this.data = data || null;
        this.content = content || null;

        this.error = null;
    };

    Response.prototype.text = function () {
        return this.content;
    };

    Response.prototype.message = function () {
        return decodeURIComponent(window.atob(this.headers['x-api-message']));
    };

    Response.prototype.setError = function (code) {
        this.error = code;
    };

    Response.prototype.getHeader = function (key, df) {
        df = typeof df === 'undefined' ? '' : df;
        return this.headers[key] || df;
    };

    let Request = function (options) {
    };

    Request.prototype.token = function () {

    };

    Request.prototype.generateUri = function (uri) {
        return Options.host + (uri.startsWith('/') ? '' : '/') + uri;
    };

    Request.prototype.get = function (uri, params, options) {
        options = options || {};
        options.headers = {
            'Content-type': 'application/x-www-form-urlencoded;charset=utf-8',
            "Authorization": 'Bearer ' + token
        };
        return this.send(uri, params, 'get', options.headers || {}, options.callback);
    };

    Request.prototype.post = function (uri, params, options) {
        options = options || {};
        options.headers = {
            'Content-type': 'application/x-www-form-urlencoded;charset=utf-8',
            "Authorization": 'Bearer ' + token
        };
        console.log(options)
        return this.send(uri, params, 'post', options.headers || {}, options.callback);
    };

    Request.prototype.put = function (uri, params, options) {
        options = options || {};
        options.headers = {
            'Content-type': 'application/x-www-form-urlencoded;charset=utf-8',
            "Authorization": 'Bearer ' + token
        };
        return this.send(uri, params, 'put', options.headers || {}, options.callback);
    };

    Request.prototype.delete = function (uri, params, options) {
        options = options || {};
        options.headers = {
            'Content-type': 'application/x-www-form-urlencoded;charset=utf-8',
            "Authorization": 'Bearer ' + token
        };
        return this.send(uri, params, 'delete', options.headers || {}, options.callback);
    };

    Request.prototype.send = function (uri, params, method, headers, onComplete) {
        method = method || 'GET';
        onComplete = onComplete || null;
        headers = headers || {};

        return new Promise((resolve, reject) => {
            dd.httpRequest({
                url: this.generateUri(uri),
                method: method.toUpperCase(),
                data: params,
                headers: headers,
                dataType: 'json',
                success: (result) => {
                    let resp = new Response(result.status, result.headers, result.data, result.originalData);
                    if (resp.status >= 200 && resp.status < 300)
                        resolve(resp);
                    else
                        reject(resp);
                },
                fail: (errCode) => {
                    let resp = new Response();
                    resp.setError(errCode);

                    reject(resp);
                },
                complete: () => {
                    if (typeof onComplete === 'function')
                        onComplete();
                }
            });
        });
    };

    let Pagination = function () {
        this.total = 1;
        this.page = 0;
        this.size = 20;
    };

    Pagination.prototype.init = function () {
        this.total = 1;
        this.page = 0;
        this.size = 20;
    };

    Pagination.prototype.hasNext = function () {
        return Math.ceil(this.total / this.size) > this.page;
    };

    Pagination.prototype.parse = function (response) {
        this.total = parseInt(response.getHeader('x-api-total', 0));
        this.page = parseInt(response.getHeader('x-api-page', 0));
        this.size = parseInt(response.getHeader('x-api-size', 20));
    };

    return {
        init: function (options) {
            options = options || {};

            for (var index in options)
                Options[index] = options[index];
        },
        create: function () {
            return new Request(Options);
        },
        pagination: function () {
            return new Pagination();
        }
    };
}

export default {
    Request: factory()
}
// App.js
import { Request } from './utils/network.js';
// console.log(Request);
Request.init({
    host: '地址'
});
App({
	request: function () {
	    return Request.create();
	},
	pager: function () {
	    return Request.pagination();
	},
});

相關文章