08335 / hivui-platform-template
hivui平台项目模板
Newer
Older
hivui-platform-template / vite-plugin / tool.js
var request = require('request');
export function isFlow(type) {
    return type.endsWith(".flow") || type.endsWith(".flowc");
}
// 接口
export function isInfc(type) {
    return type.endsWith(".infc")
}

export function isFunc(type) {
    return type.endsWith(".func")
}

export function isHtml(type) {
    return type.endsWith(".html")
}

export function isStudio(type) {
    return type.endsWith("/studio.html")
}
export function setUrlParam(path, key, value) {
    if (!key || !value) {
        return path;
    }
    if (path.indexOf("?") == -1) {
        path = `${path}?${key}=${value}`;
    } else {
        path = `${path}&${key}=${value}`;
    }
    return path;
}

export function getContentType(filePath) {
    // 去掉查询参数再解析扩展名,避免像 .woff?t=... 无法匹配的问题
    const cleanPath = (filePath || '').split('?')[0];
    const ext = cleanPath.substring(cleanPath.lastIndexOf('.')).toLowerCase();
    const contentTypes = {
        '.html': 'text/html',
        '.js': 'text/javascript',
        '.css': 'text/css',
        '.json': 'application/json',
        '.png': 'image/png',
        '.jpg': 'image/jpg',
        '.jpeg': 'image/jpeg',
        '.gif': 'image/gif',
        '.svg': 'image/svg+xml',
        '.ico': 'image/x-icon',
        '.woff': 'font/woff',
        '.woff2': 'font/woff2',
        '.ttf': 'font/ttf',
        '.eot': 'font/eot',
        '.wav': 'audio/wav',
        '.mp3': 'audio/mpeg',
        '.mp4': 'video/mp4',
        '.pdf': 'application/pdf',
        '.doc': 'application/msword',
        '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        '.xls': 'application/vnd.ms-excel',
        '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    };
    return contentTypes[ext] || 'application/octet-stream';
}


export function syncRequest(url, params, isBinary = false) {
    let options = {
        url: url,
        form: params,
        // 当请求二进制资源时,将 encoding 设为 null,返回 Buffer
        encoding: isBinary ? null : 'utf8'
    };
    return new Promise(function (resolve, reject) {
        request.get(options, function (error, response, body) {
            if (response && response.statusCode == 200) {
                resolve(body);
            } else {
                reject(error || new Error('Request failed with status ' + (response && response.statusCode)));
            }
        });
    });
}

export async function getRountMap(url) {
    let routerMap = {};
    let content = await syncRequest(url);
    if (content) {
        let body = JSON.parse(content);
        for (var i = 0; i < body.length; i++) {
            let routerPath = body[i].value;
            routerPath = routerPath.substr(routerPath.indexOf("/") + 1) + ".html"
            routerMap["/" + body[i].key] = Object.assign({
                url: routerPath
            }, body[i])
        }
    }
    return routerMap;
}