UNPKG

erest

Version:

Easy to build api server depend on @leizm/web and express.

60 lines (59 loc) 2.04 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getCallerSourceLine = getCallerSourceLine; exports.getSchemaKey = getSchemaKey; exports.jsonStringify = jsonStringify; exports.getPath = getPath; exports.getRealPath = getRealPath; exports.camelCase2underscore = camelCase2underscore; /** * @file API Utils * @author Yourtion Guo <yourtion@gmail.com> */ const node_path_1 = require("node:path"); /** 获取调用当前函数的源码地址 */ function getCallerSourceLine(dir) { const resolvedDir = (0, node_path_1.resolve)(dir); const err = new Error().stack; const stack = err ? err.split("\n").slice(1) : ""; for (let line of stack) { line = line.trim(); if (line.replace(/\\/g, "/").indexOf(resolvedDir) !== -1) { const s = line.match(/\((.*)\)\s*$/); if (s) return { relative: s[1].slice(resolvedDir.length + 1), absolute: s[1] }; } } return { relative: undefined, absolute: undefined }; } /** 获取API的Key */ function getSchemaKey(method, path, prefix) { const pf = prefix ? (prefix.indexOf("/") === 0 ? prefix : `/${camelCase2underscore(prefix)}`) : "/"; return `${method.toUpperCase()}_${(pf + path).replace(/\/\//g, "/").replace(/\/$/, "") || "/"}`; } /** 返回安全的JSON字符串 */ function jsonStringify(data, space) { // const seen: any[] = []; return JSON.stringify(data, (_, val) => { if (!val || typeof val !== "object") return val; // if (seen.indexOf(val) !== -1) return "[Circular]"; // seen.push(val); return val; }, space); } /** 获取路径 */ function getPath(def, opt) { return typeof opt === "string" ? opt : def; } /** 通过 schema key 获取 path */ function getRealPath(key) { return key.substring(key.indexOf("_") + 1); } /** 驼峰线转下划 */ function camelCase2underscore(str) { return str .replace(/^\S/, (s) => s.toLowerCase()) .replace(/([A-Z])/g, "_$1") .toLowerCase(); }