mirror of
https://gitee.com/beijing_hongye_huicheng/lilishop-uniapp.git
synced 2025-12-17 07:55:53 +08:00
commit message
This commit is contained in:
132
utils/Foundation.js
Normal file
132
utils/Foundation.js
Normal file
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* 一些常用的基础方法
|
||||
* unixToDate 将unix时间戳转换为指定格式
|
||||
* dateToUnix 将时间转unix时间戳
|
||||
* deepClone 对一个对象进行深拷贝
|
||||
* formatPrice 货币格式化
|
||||
* secrecyMobile 手机号隐私保护
|
||||
* randomString 随机生成指定长度的字符串
|
||||
*/
|
||||
|
||||
/**
|
||||
* 将unix时间戳转换为指定格式
|
||||
* @param unix 时间戳【秒】
|
||||
* @param format 转换格式
|
||||
* @returns {*|string}
|
||||
*/
|
||||
export function unixToDate(unix, format) {
|
||||
if (!unix) return unix
|
||||
let _format = format || 'yyyy-MM-dd hh:mm:ss'
|
||||
const d = new Date(unix)
|
||||
const o = {
|
||||
'M+': d.getMonth() + 1,
|
||||
'd+': d.getDate(),
|
||||
'h+': d.getHours(),
|
||||
'm+': d.getMinutes(),
|
||||
's+': d.getSeconds(),
|
||||
'q+': Math.floor((d.getMonth() + 3) / 3),
|
||||
S: d.getMilliseconds()
|
||||
}
|
||||
if (/(y+)/.test(_format)) _format = _format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length))
|
||||
for (const k in o)
|
||||
if (new RegExp('(' + k + ')').test(_format)) _format = _format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) :
|
||||
(('00' + o[k]).substr(('' + o[k]).length)))
|
||||
return _format
|
||||
}
|
||||
|
||||
/**
|
||||
* 将时间转unix时间戳
|
||||
* @param date
|
||||
* @returns {number} 【秒】
|
||||
*/
|
||||
export function dateToUnix(date) {
|
||||
let newStr = date.replace(/:/g, '-')
|
||||
newStr = newStr.replace(/ /g, '-')
|
||||
const arr = newStr.split('-')
|
||||
const datum = new Date(Date.UTC(
|
||||
arr[0],
|
||||
arr[1] - 1,
|
||||
arr[2],
|
||||
arr[3] - 8 || -8,
|
||||
arr[4] || 0,
|
||||
arr[5] || 0
|
||||
))
|
||||
return parseInt(datum.getTime() / 1000)
|
||||
}
|
||||
|
||||
/**
|
||||
* 货币格式化
|
||||
* @param price
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatPrice(price) {
|
||||
if (typeof price !== 'number') return price
|
||||
return String(Number(price).toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
||||
}
|
||||
|
||||
/**
|
||||
* 手机号隐私保护
|
||||
* 隐藏中间四位数字
|
||||
* @param mobile
|
||||
* @returns {*}
|
||||
*/
|
||||
export function secrecyMobile(mobile) {
|
||||
mobile = String(mobile)
|
||||
if (!/\d{11}/.test(mobile)) {
|
||||
return mobile
|
||||
}
|
||||
return mobile.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
|
||||
}
|
||||
|
||||
/**
|
||||
* 随机生成指定长度的字符串
|
||||
* @param length
|
||||
* @returns {string}
|
||||
*/
|
||||
export function randomString(length = 32) {
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
|
||||
const maxPos = chars.length
|
||||
let _string = ''
|
||||
for (let i = 0; i < length; i++) {
|
||||
_string += chars.charAt(Math.floor(Math.random() * maxPos))
|
||||
}
|
||||
return _string
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算传秒数的倒计时【天、时、分、秒】
|
||||
* @param seconds
|
||||
* @returns {{day : *, hours : *, minutes : *, seconds : *}}
|
||||
*/
|
||||
|
||||
export function countTimeDown(seconds) {
|
||||
const leftTime = (time) => {
|
||||
if (time < 10) time = '0' + time
|
||||
return time + ''
|
||||
}
|
||||
return {
|
||||
day: leftTime(parseInt(seconds / 60 / 60 / 24, 10)),
|
||||
hours: leftTime(parseInt(seconds / 60 / 60 % 24, 10)),
|
||||
minutes: leftTime(parseInt(seconds / 60 % 60, 10)),
|
||||
seconds: leftTime(parseInt(seconds % 60, 10))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算当前时间到第二天0点的倒计时[秒]
|
||||
* @returns {number}
|
||||
*/
|
||||
export function theNextDayTime() {
|
||||
const nowDate = new Date()
|
||||
const time = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate() + 1, 0, 0, 0).getTime() - nowDate.getTime()
|
||||
return parseInt(time / 1000)
|
||||
}
|
||||
module.exports = {
|
||||
unixToDate,
|
||||
dateToUnix,
|
||||
formatPrice,
|
||||
secrecyMobile,
|
||||
randomString,
|
||||
countTimeDown,
|
||||
theNextDayTime
|
||||
}
|
||||
47
utils/RegExp.js
Normal file
47
utils/RegExp.js
Normal file
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* 各种正则表达式
|
||||
* mobile 手机号
|
||||
* email 电子邮箱
|
||||
* password 密码【6-20位】
|
||||
* integer 正整数【不包含0】
|
||||
* money 金钱
|
||||
* TINumber 纳税识别号
|
||||
* IDCard 身份证
|
||||
* userName 账户名称【汉字、字母、数字、“-”、“_”的组合】
|
||||
* URL URL
|
||||
* TEL 固定电话
|
||||
*/
|
||||
|
||||
// 手机号
|
||||
export const mobile = /^0?(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$/
|
||||
|
||||
// 电子邮箱
|
||||
export const email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
|
||||
|
||||
// 密码【6-20位】
|
||||
export const password = /^[@A-Za-z0-9!#$%^&*.~,]{6,20}$/
|
||||
|
||||
// 正整数【不包含0】
|
||||
export const integer = /^[1-9]\d*$/
|
||||
|
||||
// 正整数【包含0】
|
||||
export const Integer = /^[0-9]\d*$/
|
||||
|
||||
// 金钱
|
||||
export const money = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
|
||||
|
||||
// 纳税识别号
|
||||
export const TINumber = /^((\d{6}[0-9A-Z]{9})|([0-9A-Za-z]{2}\d{6}[0-9A-Za-z]{10,12}))$/
|
||||
|
||||
// 身份证
|
||||
export const IDCard = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
|
||||
|
||||
// 账户名称【汉字、字母、数字、“-”、“_”的组合】
|
||||
export const userName = /[A-Za-z0-9_\-\u4e00-\u9fa5]$/
|
||||
|
||||
// URL
|
||||
export const URL =
|
||||
/^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
|
||||
|
||||
// 固话
|
||||
export const TEL = /0\d{2,3}-\d{7,8}/
|
||||
118
utils/filters.js
Normal file
118
utils/filters.js
Normal file
@@ -0,0 +1,118 @@
|
||||
import Foundation from "./Foundation.js";
|
||||
import storage from "@/utils/storage.js";
|
||||
/**
|
||||
* 金钱单位置换 2999 --> 2,999.00
|
||||
* @param val
|
||||
* @param unit
|
||||
* @param location
|
||||
* @returns {*}
|
||||
*/
|
||||
export function unitPrice(val, unit, location) {
|
||||
if (!val) val = 0;
|
||||
let price = Foundation.formatPrice(val);
|
||||
if (location === "before") {
|
||||
return price.substr(0, price.length - 3);
|
||||
}
|
||||
if (location === "after") {
|
||||
return price.substr(-2);
|
||||
}
|
||||
return (unit || "") + price;
|
||||
}
|
||||
|
||||
/**
|
||||
* 脱敏姓名
|
||||
*/
|
||||
|
||||
export function noPassByName(str) {
|
||||
if (null != str && str != undefined) {
|
||||
if (str.length <= 3) {
|
||||
return "*" + str.substring(1, str.length);
|
||||
} else if (str.length > 3 && str.length <= 6) {
|
||||
return "**" + str.substring(2, str.length);
|
||||
} else if (str.length > 6) {
|
||||
return str.substring(0, 2) + "****" + str.substring(6, str.length);
|
||||
}
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理unix时间戳,转换为可阅读时间格式
|
||||
* @param unix
|
||||
* @param format
|
||||
* @returns {*|string}
|
||||
*/
|
||||
export function unixToDate(unix, format) {
|
||||
let _format = format || "yyyy-MM-dd hh:mm:ss";
|
||||
const d = new Date(unix * 1000);
|
||||
const o = {
|
||||
"M+": d.getMonth() + 1,
|
||||
"d+": d.getDate(),
|
||||
"h+": d.getHours(),
|
||||
"m+": d.getMinutes(),
|
||||
"s+": d.getSeconds(),
|
||||
"q+": Math.floor((d.getMonth() + 3) / 3),
|
||||
S: d.getMilliseconds(),
|
||||
};
|
||||
if (/(y+)/.test(_format))
|
||||
_format = _format.replace(
|
||||
RegExp.$1,
|
||||
(d.getFullYear() + "").substr(4 - RegExp.$1.length)
|
||||
);
|
||||
for (const k in o)
|
||||
if (new RegExp("(" + k + ")").test(_format))
|
||||
_format = _format.replace(
|
||||
RegExp.$1,
|
||||
RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
|
||||
);
|
||||
return _format;
|
||||
}
|
||||
|
||||
/**
|
||||
* 13888888888 -> 138****8888
|
||||
* @param mobile
|
||||
* @returns {*}
|
||||
*/
|
||||
export function secrecyMobile(mobile) {
|
||||
mobile = String(mobile);
|
||||
if (!/\d{11}/.test(mobile)) {
|
||||
return mobile;
|
||||
}
|
||||
return mobile.replace(/(\d{3})(\d{4})(\d{4})/, "$1****$3");
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除逗号
|
||||
*
|
||||
*/
|
||||
export function clearStrComma(str) {
|
||||
str = str.replace(/,/g, ""); //取消字符串中出现的所有逗号
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断用户是否登录
|
||||
* @param val 如果为auth则判断是否登录
|
||||
* 如果传入 auth 则为判断是否登录
|
||||
*/
|
||||
export function isLogin(val) {
|
||||
let userInfo = storage.getUserInfo();
|
||||
if (val == "auth") {
|
||||
return userInfo.id ? true : false;
|
||||
} else {
|
||||
return storage.getUserInfo();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前加载的页面对象
|
||||
* @param val
|
||||
*/
|
||||
export function getPages(val) {
|
||||
const pages = getCurrentPages(); //获取加载的页面
|
||||
const currentPage = pages[pages.length - 1]; //获取当前页面的对象
|
||||
const url = currentPage.route; //当前页面url
|
||||
|
||||
return val ? currentPage : url;
|
||||
}
|
||||
223
utils/md5.js
Normal file
223
utils/md5.js
Normal file
@@ -0,0 +1,223 @@
|
||||
/*
|
||||
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
|
||||
* Digest Algorithm, as defined in RFC 1321.
|
||||
* Version 1.1 Copyright (C) Paul Johnston 1999 - 2002.
|
||||
* Code also contributed by Greg Holt
|
||||
* See http://pajhome.org.uk/site/legal.html for details.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
|
||||
* to work around bugs in some JS interpreters.
|
||||
*/
|
||||
function safe_add(x, y) {
|
||||
var lsw = (x & 0xFFFF) + (y & 0xFFFF)
|
||||
var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
|
||||
return (msw << 16) | (lsw & 0xFFFF)
|
||||
}
|
||||
|
||||
/*
|
||||
* Bitwise rotate a 32-bit number to the left.
|
||||
*/
|
||||
function rol(num, cnt) {
|
||||
return (num << cnt) | (num >>> (32 - cnt))
|
||||
}
|
||||
|
||||
/*
|
||||
* These functions implement the four basic operations the algorithm uses.
|
||||
*/
|
||||
function cmn(q, a, b, x, s, t) {
|
||||
return safe_add(rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
|
||||
}
|
||||
|
||||
function ff(a, b, c, d, x, s, t) {
|
||||
return cmn((b & c) | ((~b) & d), a, b, x, s, t)
|
||||
}
|
||||
|
||||
function gg(a, b, c, d, x, s, t) {
|
||||
return cmn((b & d) | (c & (~d)), a, b, x, s, t)
|
||||
}
|
||||
|
||||
function hh(a, b, c, d, x, s, t) {
|
||||
return cmn(b ^ c ^ d, a, b, x, s, t)
|
||||
}
|
||||
|
||||
function ii(a, b, c, d, x, s, t) {
|
||||
return cmn(c ^ (b | (~d)), a, b, x, s, t)
|
||||
}
|
||||
|
||||
/*
|
||||
* Calculate the MD5 of an array of little-endian words, producing an array
|
||||
* of little-endian words.
|
||||
*/
|
||||
function coreMD5(x) {
|
||||
var a = 1732584193
|
||||
var b = -271733879
|
||||
var c = -1732584194
|
||||
var d = 271733878
|
||||
|
||||
for (var i = 0; i < x.length; i += 16) {
|
||||
var olda = a
|
||||
var oldb = b
|
||||
var oldc = c
|
||||
var oldd = d
|
||||
|
||||
a = ff(a, b, c, d, x[i + 0], 7, -680876936)
|
||||
d = ff(d, a, b, c, x[i + 1], 12, -389564586)
|
||||
c = ff(c, d, a, b, x[i + 2], 17, 606105819)
|
||||
b = ff(b, c, d, a, x[i + 3], 22, -1044525330)
|
||||
a = ff(a, b, c, d, x[i + 4], 7, -176418897)
|
||||
d = ff(d, a, b, c, x[i + 5], 12, 1200080426)
|
||||
c = ff(c, d, a, b, x[i + 6], 17, -1473231341)
|
||||
b = ff(b, c, d, a, x[i + 7], 22, -45705983)
|
||||
a = ff(a, b, c, d, x[i + 8], 7, 1770035416)
|
||||
d = ff(d, a, b, c, x[i + 9], 12, -1958414417)
|
||||
c = ff(c, d, a, b, x[i + 10], 17, -42063)
|
||||
b = ff(b, c, d, a, x[i + 11], 22, -1990404162)
|
||||
a = ff(a, b, c, d, x[i + 12], 7, 1804603682)
|
||||
d = ff(d, a, b, c, x[i + 13], 12, -40341101)
|
||||
c = ff(c, d, a, b, x[i + 14], 17, -1502002290)
|
||||
b = ff(b, c, d, a, x[i + 15], 22, 1236535329)
|
||||
|
||||
a = gg(a, b, c, d, x[i + 1], 5, -165796510)
|
||||
d = gg(d, a, b, c, x[i + 6], 9, -1069501632)
|
||||
c = gg(c, d, a, b, x[i + 11], 14, 643717713)
|
||||
b = gg(b, c, d, a, x[i + 0], 20, -373897302)
|
||||
a = gg(a, b, c, d, x[i + 5], 5, -701558691)
|
||||
d = gg(d, a, b, c, x[i + 10], 9, 38016083)
|
||||
c = gg(c, d, a, b, x[i + 15], 14, -660478335)
|
||||
b = gg(b, c, d, a, x[i + 4], 20, -405537848)
|
||||
a = gg(a, b, c, d, x[i + 9], 5, 568446438)
|
||||
d = gg(d, a, b, c, x[i + 14], 9, -1019803690)
|
||||
c = gg(c, d, a, b, x[i + 3], 14, -187363961)
|
||||
b = gg(b, c, d, a, x[i + 8], 20, 1163531501)
|
||||
a = gg(a, b, c, d, x[i + 13], 5, -1444681467)
|
||||
d = gg(d, a, b, c, x[i + 2], 9, -51403784)
|
||||
c = gg(c, d, a, b, x[i + 7], 14, 1735328473)
|
||||
b = gg(b, c, d, a, x[i + 12], 20, -1926607734)
|
||||
|
||||
a = hh(a, b, c, d, x[i + 5], 4, -378558)
|
||||
d = hh(d, a, b, c, x[i + 8], 11, -2022574463)
|
||||
c = hh(c, d, a, b, x[i + 11], 16, 1839030562)
|
||||
b = hh(b, c, d, a, x[i + 14], 23, -35309556)
|
||||
a = hh(a, b, c, d, x[i + 1], 4, -1530992060)
|
||||
d = hh(d, a, b, c, x[i + 4], 11, 1272893353)
|
||||
c = hh(c, d, a, b, x[i + 7], 16, -155497632)
|
||||
b = hh(b, c, d, a, x[i + 10], 23, -1094730640)
|
||||
a = hh(a, b, c, d, x[i + 13], 4, 681279174)
|
||||
d = hh(d, a, b, c, x[i + 0], 11, -358537222)
|
||||
c = hh(c, d, a, b, x[i + 3], 16, -722521979)
|
||||
b = hh(b, c, d, a, x[i + 6], 23, 76029189)
|
||||
a = hh(a, b, c, d, x[i + 9], 4, -640364487)
|
||||
d = hh(d, a, b, c, x[i + 12], 11, -421815835)
|
||||
c = hh(c, d, a, b, x[i + 15], 16, 530742520)
|
||||
b = hh(b, c, d, a, x[i + 2], 23, -995338651)
|
||||
|
||||
a = ii(a, b, c, d, x[i + 0], 6, -198630844)
|
||||
d = ii(d, a, b, c, x[i + 7], 10, 1126891415)
|
||||
c = ii(c, d, a, b, x[i + 14], 15, -1416354905)
|
||||
b = ii(b, c, d, a, x[i + 5], 21, -57434055)
|
||||
a = ii(a, b, c, d, x[i + 12], 6, 1700485571)
|
||||
d = ii(d, a, b, c, x[i + 3], 10, -1894986606)
|
||||
c = ii(c, d, a, b, x[i + 10], 15, -1051523)
|
||||
b = ii(b, c, d, a, x[i + 1], 21, -2054922799)
|
||||
a = ii(a, b, c, d, x[i + 8], 6, 1873313359)
|
||||
d = ii(d, a, b, c, x[i + 15], 10, -30611744)
|
||||
c = ii(c, d, a, b, x[i + 6], 15, -1560198380)
|
||||
b = ii(b, c, d, a, x[i + 13], 21, 1309151649)
|
||||
a = ii(a, b, c, d, x[i + 4], 6, -145523070)
|
||||
d = ii(d, a, b, c, x[i + 11], 10, -1120210379)
|
||||
c = ii(c, d, a, b, x[i + 2], 15, 718787259)
|
||||
b = ii(b, c, d, a, x[i + 9], 21, -343485551)
|
||||
|
||||
a = safe_add(a, olda)
|
||||
b = safe_add(b, oldb)
|
||||
c = safe_add(c, oldc)
|
||||
d = safe_add(d, oldd)
|
||||
}
|
||||
return [a, b, c, d]
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert an array of little-endian words to a hex string.
|
||||
*/
|
||||
function binl2hex(binarray) {
|
||||
var hex_tab = "0123456789abcdef"
|
||||
var str = ""
|
||||
for (var i = 0; i < binarray.length * 4; i++) {
|
||||
str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +
|
||||
hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF)
|
||||
}
|
||||
return str
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert an array of little-endian words to a base64 encoded string.
|
||||
*/
|
||||
function binl2b64(binarray) {
|
||||
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||
var str = ""
|
||||
for (var i = 0; i < binarray.length * 32; i += 6) {
|
||||
str += tab.charAt(((binarray[i >> 5] << (i % 32)) & 0x3F) |
|
||||
((binarray[i >> 5 + 1] >> (32 - i % 32)) & 0x3F))
|
||||
}
|
||||
return str
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert an 8-bit character string to a sequence of 16-word blocks, stored
|
||||
* as an array, and append appropriate padding for MD4/5 calculation.
|
||||
* If any of the characters are >255, the high byte is silently ignored.
|
||||
*/
|
||||
function str2binl(str) {
|
||||
var nblk = ((str.length + 8) >> 6) + 1 // number of 16-word blocks
|
||||
var blks = new Array(nblk * 16)
|
||||
for (var i = 0; i < nblk * 16; i++) blks[i] = 0
|
||||
for (var i = 0; i < str.length; i++)
|
||||
blks[i >> 2] |= (str.charCodeAt(i) & 0xFF) << ((i % 4) * 8)
|
||||
blks[i >> 2] |= 0x80 << ((i % 4) * 8)
|
||||
blks[nblk * 16 - 2] = str.length * 8
|
||||
return blks
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert a wide-character string to a sequence of 16-word blocks, stored as
|
||||
* an array, and append appropriate padding for MD4/5 calculation.
|
||||
*/
|
||||
function strw2binl(str) {
|
||||
var nblk = ((str.length + 4) >> 5) + 1 // number of 16-word blocks
|
||||
var blks = new Array(nblk * 16)
|
||||
for (var i = 0; i < nblk * 16; i++) blks[i] = 0
|
||||
for (var i = 0; i < str.length; i++)
|
||||
blks[i >> 1] |= str.charCodeAt(i) << ((i % 2) * 16)
|
||||
blks[i >> 1] |= 0x80 << ((i % 2) * 16)
|
||||
blks[nblk * 16 - 2] = str.length * 16
|
||||
return blks
|
||||
}
|
||||
|
||||
/*
|
||||
* External interface
|
||||
*/
|
||||
function hexMD5(str) {
|
||||
return binl2hex(coreMD5(str2binl(str)))
|
||||
}
|
||||
|
||||
function hexMD5w(str) {
|
||||
return binl2hex(coreMD5(strw2binl(str)))
|
||||
}
|
||||
|
||||
function b64MD5(str) {
|
||||
return binl2b64(coreMD5(str2binl(str)))
|
||||
}
|
||||
|
||||
function b64MD5w(str) {
|
||||
return binl2b64(coreMD5(strw2binl(str)))
|
||||
}
|
||||
/* Backward compatibility */
|
||||
function calcMD5(str) {
|
||||
return binl2hex(coreMD5(str2binl(str)))
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
md5: hexMD5
|
||||
}
|
||||
210
utils/request.js
Normal file
210
utils/request.js
Normal file
@@ -0,0 +1,210 @@
|
||||
import Request from "@/lib/request/index.js";
|
||||
import { configHandle } from "@/utils/tools.js";
|
||||
import { refreshTokenFn } from "@/api/login.js";
|
||||
import storage from "@/utils/storage.js";
|
||||
import { md5 } from "@/utils/md5.js";
|
||||
import Foundation from "@/utils/Foundation.js";
|
||||
import api from "@/config/api.js";
|
||||
|
||||
import uuid from "@/utils/uuid.modified.js";
|
||||
|
||||
/**
|
||||
* 无痛刷新token思路(如果不使用无痛刷新token,忽略此处注释)
|
||||
* 看了很多,有个问题一直得不到解决----‘多个接口请求,token失效,如何让获取token只获取一遍’、
|
||||
* 于是想到了闭包防抖......
|
||||
* 本方案并不是最佳方案,只是给你们提供一种思路。如果你有完美解决方案,可以分享一下
|
||||
*/
|
||||
const expireToken = []; // 储存过期的token
|
||||
|
||||
// 防抖闭包来一波
|
||||
function getTokenDebounce() {
|
||||
let lock = false;
|
||||
let success = false;
|
||||
return async function () {
|
||||
if (!lock) {
|
||||
lock = true;
|
||||
console.log('dd')
|
||||
await refreshTokenFn(storage.getRefreshToken())
|
||||
.then((res) => {
|
||||
|
||||
if (res.data.success) {
|
||||
let { accessToken, refreshToken } = res.data.result;
|
||||
storage.setAccessToken(accessToken);
|
||||
storage.setRefreshToken(refreshToken);
|
||||
success = true;
|
||||
lock = false;
|
||||
} else {
|
||||
|
||||
cleanStorage();
|
||||
success = false;
|
||||
lock = false;
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error)
|
||||
cleanStorage();
|
||||
success = false;
|
||||
lock = false;
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
// XXX 我只能想到通过轮询来看获取新的token是否结束,有好的方案可以说。一直看lock,直到请求失败或者成功
|
||||
const timer = setInterval(() => {
|
||||
if (!lock) {
|
||||
clearInterval(timer);
|
||||
|
||||
if (success) {
|
||||
|
||||
resolve("success");
|
||||
} else {
|
||||
cleanStorage();
|
||||
resolve("fail");
|
||||
}
|
||||
}
|
||||
}, 100); // 轮询时间可以自己看改成多少合适
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function cleanStorage() {
|
||||
uni.showToast({
|
||||
title: "你的登录状态已过期,请重新登录",
|
||||
icon: "none",
|
||||
duration: 1500,
|
||||
});
|
||||
if(uni.showLoading()){ uni.hideLoading();}
|
||||
|
||||
storage.setHasLogin(false);
|
||||
storage.setAccessToken("");
|
||||
storage.setRefreshToken("");
|
||||
storage.setUuid("");
|
||||
storage.setUserInfo({});
|
||||
|
||||
uni.navigateTo({
|
||||
url: "/pages/passport/login",
|
||||
});
|
||||
}
|
||||
|
||||
let http = new Request();
|
||||
const refreshToken = getTokenDebounce();
|
||||
const reReqest = new Request();
|
||||
|
||||
http.setConfig((config) => {
|
||||
// 没有uuid创建
|
||||
if (!storage.getUuid()) {
|
||||
storage.setUuid(uuid.v1());
|
||||
}
|
||||
|
||||
/* 设置全局配置 */
|
||||
config.baseURL = api.buyer;
|
||||
config.header = {
|
||||
...config.header,
|
||||
};
|
||||
config.validateStatus = (statusCode) => {
|
||||
// 不论什么状态,统一在正确中处理
|
||||
return true;
|
||||
};
|
||||
return config;
|
||||
});
|
||||
|
||||
http.interceptors.request.use(
|
||||
(config) => {
|
||||
/* 请求之前拦截器。可以使用async await 做异步操作 */
|
||||
let accessToken = storage.getAccessToken();
|
||||
if (accessToken) {
|
||||
const nonce = Foundation.randomString(6);
|
||||
const timestamp = parseInt(new Date().getTime() / 1000);
|
||||
const sign = md5(nonce + timestamp + accessToken);
|
||||
const _params = {
|
||||
nonce,
|
||||
timestamp,
|
||||
sign,
|
||||
};
|
||||
let params = config.params || {};
|
||||
params = { ...params, ..._params };
|
||||
config.params = params;
|
||||
config.header.accessToken = accessToken;
|
||||
}
|
||||
config.header = {
|
||||
...config.header,
|
||||
uuid: storage.getUuid() || uuid.v1(),
|
||||
};
|
||||
return config;
|
||||
},
|
||||
(config) => {
|
||||
return Promise.reject(config);
|
||||
}
|
||||
);
|
||||
|
||||
// 必须使用异步函数,注意
|
||||
http.interceptors.response.use(
|
||||
async (response) => {
|
||||
/* 请求之后拦截器。可以使用async await 做异步操作 */
|
||||
// token存在并且token过期
|
||||
let token = storage.getAccessToken();
|
||||
|
||||
if (token && response.statusCode === 403) {
|
||||
expireToken.includes(token) ?cleanStorage() :""
|
||||
// jwt token 过期了
|
||||
expireToken.push(token); // 把过期token 储存
|
||||
|
||||
const currentToken = storage.getAccessToken();
|
||||
|
||||
if (expireToken.includes(currentToken)) {
|
||||
|
||||
// 本地储存的是过期token了,重新获取
|
||||
const getTokenResult = await refreshToken();
|
||||
|
||||
if (getTokenResult === "success") {
|
||||
// 获取新的token成功
|
||||
|
||||
try {
|
||||
const repeatRes = await reReqest.request(
|
||||
configHandle(response.config)
|
||||
);
|
||||
response = repeatRes;
|
||||
} catch (err) {
|
||||
|
||||
}
|
||||
} else {
|
||||
cleanStorage();
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
const repeatRes = await reReqest.request(
|
||||
configHandle(response.config)
|
||||
);
|
||||
|
||||
response = repeatRes;
|
||||
} catch (err) {
|
||||
cleanStorage();
|
||||
}
|
||||
}
|
||||
} else if (response.statusCode === 403 || response.data.code === 403) {
|
||||
cleanStorage();
|
||||
} else if (response.statusCode == 200 && !response.data.success) {
|
||||
uni.showToast({
|
||||
title: response.data.message,
|
||||
icon: "none",
|
||||
duration: 1500,
|
||||
});
|
||||
|
||||
}
|
||||
return response;
|
||||
},
|
||||
(error) => {
|
||||
// 请求错误做点什么。可以使用async await 做异步操作
|
||||
return response;
|
||||
}
|
||||
);
|
||||
|
||||
export { http };
|
||||
|
||||
export const Method = {
|
||||
GET: "GET",
|
||||
POST: "POST",
|
||||
PUT: "PUT",
|
||||
DELETE: "DELETE",
|
||||
};
|
||||
85
utils/storage.js
Normal file
85
utils/storage.js
Normal file
@@ -0,0 +1,85 @@
|
||||
let isDev = process.env.NODE_ENV === "development";
|
||||
|
||||
const UUID = isDev ? "uuid_key_dev" : "uuid_key";
|
||||
const HAS_LOGIN = isDev ? "has_login_key_dev" : "has_login_key";
|
||||
const ACCESS_TOKEN = isDev ? "access_token_key_dev" : "access_token_key";
|
||||
const REFRESH_TOKEN = isDev ? "refresh_token_key_dev" : "refresh_token_key";
|
||||
const USER_INFO = isDev ? "user_info_obj_dev" : "user_info_obj";
|
||||
const FACE_LOGIN = isDev ? "face_login_dev" : "face_login";
|
||||
const FINGER_LOGIN = isDev ? "finger_login_dev" : "finger_login";
|
||||
const CART_BACKBTN = isDev ? "cart_backbtn_dev" : "cart_backbtn";
|
||||
export default {
|
||||
// 获取face id登录
|
||||
getFaceLogin() {
|
||||
return uni.getStorageSync(FACE_LOGIN);
|
||||
},
|
||||
// 写入face id
|
||||
setFaceLogin(val) {
|
||||
uni.setStorageSync(FACE_LOGIN, val);
|
||||
},
|
||||
// 获取指纹登录
|
||||
getFingerLogin() {
|
||||
return uni.getStorageSync(FINGER_LOGIN);
|
||||
},
|
||||
// 写入指纹登录
|
||||
setFingerLogin(val) {
|
||||
uni.setStorageSync(FINGER_LOGIN, val);
|
||||
},
|
||||
// 写入用户信息
|
||||
setUserInfo(val) {
|
||||
uni.setStorageSync(USER_INFO, val);
|
||||
},
|
||||
// 获取用户信息
|
||||
getUserInfo() {
|
||||
return uni.getStorageSync(USER_INFO);
|
||||
},
|
||||
// 写入uuid
|
||||
setUuid(val) {
|
||||
uni.setStorageSync(UUID, val);
|
||||
},
|
||||
// 获取uuid
|
||||
getUuid() {
|
||||
return uni.getStorageSync(UUID);
|
||||
},
|
||||
// 写入登录
|
||||
setHasLogin(val) {
|
||||
uni.setStorageSync(HAS_LOGIN, val);
|
||||
},
|
||||
// 获取是否登录
|
||||
getHasLogin() {
|
||||
return uni.getStorageSync(HAS_LOGIN);
|
||||
},
|
||||
// 删除uuid
|
||||
removeUuid() {
|
||||
uni.removeStorageSync(UUID);
|
||||
},
|
||||
// 写入accessToken
|
||||
setAccessToken(val) {
|
||||
uni.setStorageSync(ACCESS_TOKEN, val);
|
||||
},
|
||||
// 获取accessToken
|
||||
getAccessToken() {
|
||||
return uni.getStorageSync(ACCESS_TOKEN);
|
||||
},
|
||||
// 后退购物车
|
||||
setCartBackbtn(val) {
|
||||
uni.setStorageSync(CART_BACKBTN, val);
|
||||
},
|
||||
|
||||
// 删除token
|
||||
removeAccessToken() {
|
||||
uni.removeStorageSync(ACCESS_TOKEN);
|
||||
},
|
||||
// 写入刷新token
|
||||
setRefreshToken(val) {
|
||||
uni.setStorageSync(REFRESH_TOKEN, val);
|
||||
},
|
||||
// 获取刷新token
|
||||
getRefreshToken() {
|
||||
return uni.getStorageSync(REFRESH_TOKEN);
|
||||
},
|
||||
// 删除token
|
||||
removeRefreshToken() {
|
||||
uni.removeStorageSync(REFRESH_TOKEN);
|
||||
},
|
||||
};
|
||||
143
utils/tools.js
Normal file
143
utils/tools.js
Normal file
@@ -0,0 +1,143 @@
|
||||
import Foundation from '@/utils/Foundation.js';
|
||||
import {
|
||||
md5
|
||||
} from '@/utils/md5.js';
|
||||
import storage from "@/utils/storage.js";
|
||||
import store from "@/store/index.js";
|
||||
|
||||
// 重新整理一下config
|
||||
const configHandle = (config) => {
|
||||
// 'development', 'production'
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
const nonce = Foundation.randomString(6)
|
||||
const timestamp = parseInt(new Date().getTime() / 1000)
|
||||
const sign = md5( nonce + timestamp + storage.getAccessToken())
|
||||
if (config.url.indexOf('?') === -1) {
|
||||
config.url = `${config.url}?&nonce=${nonce}×tamp=${timestamp}&sign=${sign}`
|
||||
} else {
|
||||
let params = urlParse(config.url);
|
||||
console.info(params);
|
||||
let url = config.url.split('?')[0];
|
||||
params = { ...params,
|
||||
nonce,
|
||||
timestamp,
|
||||
sign
|
||||
};
|
||||
let str = '';
|
||||
for (var k in params) {
|
||||
console.info(k, params[k])
|
||||
str += '&' + k + '=' + params[k];
|
||||
}
|
||||
str = str.substr(1);
|
||||
config.url = `${url}?${str}`;
|
||||
}
|
||||
config.header = {
|
||||
...config.header,
|
||||
uuid: storage.getUuid()
|
||||
}
|
||||
} else {
|
||||
config.header = {
|
||||
...config.header,
|
||||
Authorization: storage.getAccessToken(),
|
||||
uuid: storage.getUuid()
|
||||
}
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析url参数
|
||||
* @example ?id=12345&a=b
|
||||
* @return Object {id:12345,a:b}
|
||||
*/
|
||||
function urlParse(url) {
|
||||
let obj = {};
|
||||
let reg = /[?&][^?&]+=[^?&]+/g;
|
||||
let arr = url.match(reg);
|
||||
if (arr) {
|
||||
arr.forEach((item) => {
|
||||
let tempArr = item.substring(1).split('=');
|
||||
let key = decodeURIComponent(tempArr[0]);
|
||||
let val = decodeURIComponent(tempArr.splice(1).join('='));
|
||||
obj[key] = val;
|
||||
});
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
|
||||
const getNetworkType = () => {
|
||||
uni.getNetworkType({
|
||||
success: (res) => {
|
||||
if (res.networkType === 'none') {
|
||||
uni.showToast({
|
||||
title: '网络好像有点问题,请检查后重试!',
|
||||
duration: 2000,
|
||||
icon: 'none'
|
||||
});
|
||||
let pages = getCurrentPages();
|
||||
if (pages.length) {
|
||||
let route = pages[pages.length - 1].route;
|
||||
if (route !== 'pages/empty/empty') {
|
||||
uni.navigateTo({
|
||||
url: `/pages/empty/empty?type=wifi`
|
||||
})
|
||||
}
|
||||
}else{
|
||||
uni.navigateTo({
|
||||
url: `/pages/empty/empty?type=wifi`
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const throttle = (fn, that, gapTime) => {
|
||||
// export function throttle(fn, gapTime) {
|
||||
if (gapTime == null || gapTime == undefined) {
|
||||
gapTime = 1800
|
||||
}
|
||||
let _lastTime = that.lastTime
|
||||
let _nowTime = +new Date()
|
||||
if (_nowTime - _lastTime > gapTime || !_lastTime) {
|
||||
fn.apply(that, arguments) //将this和参数传给原函数
|
||||
that.lastTime = _nowTime
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算传秒数的倒计时【天、时、分、秒】
|
||||
* @param seconds
|
||||
* @returns {{day : *, hours : *, minutes : *, seconds : *}}
|
||||
*/
|
||||
const countTimeDown = (seconds) => {
|
||||
const leftTime = (time) => {
|
||||
if (time < 10) time = '0' + time
|
||||
return time + ''
|
||||
}
|
||||
return {
|
||||
day: leftTime(parseInt(seconds / 60 / 60 / 24, 10)),
|
||||
hours: leftTime(parseInt(seconds / 60 / 60 % 24, 10)),
|
||||
minutes: leftTime(parseInt(seconds / 60 % 60, 10)),
|
||||
seconds: leftTime(parseInt(seconds % 60, 10))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算当前时间到第二天0点的倒计时[秒]
|
||||
* @returns {number}
|
||||
*/
|
||||
const theNextDayTime = () => {
|
||||
const nowDate = new Date()
|
||||
const time = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate() + 1, 0, 0, 0).getTime() -
|
||||
nowDate.getTime()
|
||||
return parseInt(time / 1000)
|
||||
}
|
||||
|
||||
export {
|
||||
//configHandle,
|
||||
getNetworkType,
|
||||
throttle,
|
||||
countTimeDown,
|
||||
theNextDayTime
|
||||
}
|
||||
262
utils/uuid.modified.js
Normal file
262
utils/uuid.modified.js
Normal file
@@ -0,0 +1,262 @@
|
||||
// uuid.js
|
||||
//
|
||||
// Copyright (c) 2010-2012 Robert Kieffer
|
||||
// MIT License - http://opensource.org/licenses/mit-license.php
|
||||
|
||||
/*global window, require, define */
|
||||
(function(_window) {
|
||||
'use strict';
|
||||
|
||||
|
||||
|
||||
// Unique ID creation requires a high quality random # generator. We feature
|
||||
// detect to determine the best RNG source, normalizing to a function that
|
||||
// returns 128-bits of randomness, since that's what's usually required
|
||||
var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;
|
||||
|
||||
function setupBrowser() {
|
||||
// Allow for MSIE11 msCrypto
|
||||
//var _crypto = _window.crypto || _window.msCrypto;
|
||||
var crypto = {}
|
||||
var _crypto = crypto || _window.crypto || _window.msCrypto;
|
||||
|
||||
if (!_rng && _crypto && _crypto.getRandomValues) {
|
||||
// WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
|
||||
//
|
||||
// Moderately fast, high quality
|
||||
try {
|
||||
var _rnds8 = new Uint8Array(16);
|
||||
_whatwgRNG = _rng = function whatwgRNG() {
|
||||
_crypto.getRandomValues(_rnds8);
|
||||
return _rnds8;
|
||||
};
|
||||
|
||||
_rng();
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
if (!_rng) {
|
||||
// Math.random()-based (RNG)
|
||||
//
|
||||
// If all else fails, use Math.random(). It's fast, but is of unspecified
|
||||
// quality.
|
||||
var _rnds = new Array(16);
|
||||
_mathRNG = _rng = function() {
|
||||
for (var i = 0, r; i < 16; i++) {
|
||||
if ((i & 0x03) === 0) { r = Math.random() * 0x100000000; }
|
||||
_rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
|
||||
}
|
||||
|
||||
return _rnds;
|
||||
};
|
||||
if ('undefined' !== typeof console && console.warn) {
|
||||
// console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setupBrowser();
|
||||
|
||||
// Buffer class to use
|
||||
var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;
|
||||
|
||||
// Maps for number <-> hex string conversion
|
||||
var _byteToHex = [];
|
||||
var _hexToByte = {};
|
||||
for (var i = 0; i < 256; i++) {
|
||||
_byteToHex[i] = (i + 0x100).toString(16).substr(1);
|
||||
_hexToByte[_byteToHex[i]] = i;
|
||||
}
|
||||
|
||||
// **`parse()` - Parse a UUID into it's component bytes**
|
||||
function parse(s, buf, offset) {
|
||||
var i = (buf && offset) || 0,
|
||||
ii = 0;
|
||||
|
||||
buf = buf || [];
|
||||
s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
|
||||
if (ii < 16) { // Don't overflow!
|
||||
buf[i + ii++] = _hexToByte[oct];
|
||||
}
|
||||
});
|
||||
|
||||
// Zero out remaining bytes if string was short
|
||||
while (ii < 16) {
|
||||
buf[i + ii++] = 0;
|
||||
}
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
// **`unparse()` - Convert UUID byte array (ala parse()) into a string**
|
||||
function unparse(buf, offset) {
|
||||
var i = offset || 0,
|
||||
bth = _byteToHex;
|
||||
return bth[buf[i++]] + bth[buf[i++]] +
|
||||
bth[buf[i++]] + bth[buf[i++]] + '-' +
|
||||
bth[buf[i++]] + bth[buf[i++]] + '-' +
|
||||
bth[buf[i++]] + bth[buf[i++]] + '-' +
|
||||
bth[buf[i++]] + bth[buf[i++]] + '-' +
|
||||
bth[buf[i++]] + bth[buf[i++]] +
|
||||
bth[buf[i++]] + bth[buf[i++]] +
|
||||
bth[buf[i++]] + bth[buf[i++]];
|
||||
}
|
||||
|
||||
// **`v1()` - Generate time-based UUID**
|
||||
//
|
||||
// Inspired by https://github.com/LiosK/UUID.js
|
||||
// and http://docs.python.org/library/uuid.html
|
||||
|
||||
// random #'s we need to init node and clockseq
|
||||
var _seedBytes = _rng();
|
||||
|
||||
// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
|
||||
var _nodeId = [
|
||||
_seedBytes[0] | 0x01,
|
||||
_seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
|
||||
];
|
||||
|
||||
// Per 4.2.2, randomize (14 bit) clockseq
|
||||
var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
|
||||
|
||||
// Previous uuid creation time
|
||||
var _lastMSecs = 0,
|
||||
_lastNSecs = 0;
|
||||
|
||||
// See https://github.com/broofa/node-uuid for API details
|
||||
function v1(options, buf, offset) {
|
||||
var i = buf && offset || 0;
|
||||
var b = buf || [];
|
||||
|
||||
options = options || {};
|
||||
|
||||
var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;
|
||||
|
||||
// UUID timestamps are 100 nano-second units since the Gregorian epoch,
|
||||
// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
|
||||
// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
|
||||
// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
|
||||
var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();
|
||||
|
||||
// Per 4.2.1.2, use count of uuid's generated during the current clock
|
||||
// cycle to simulate higher resolution clock
|
||||
var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;
|
||||
|
||||
// Time since last uuid creation (in msecs)
|
||||
var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs) / 10000;
|
||||
|
||||
// Per 4.2.1.2, Bump clockseq on clock regression
|
||||
if (dt < 0 && options.clockseq == null) {
|
||||
clockseq = clockseq + 1 & 0x3fff;
|
||||
}
|
||||
|
||||
// Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
|
||||
// time interval
|
||||
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {
|
||||
nsecs = 0;
|
||||
}
|
||||
|
||||
// Per 4.2.1.2 Throw error if too many uuids are requested
|
||||
if (nsecs >= 10000) {
|
||||
throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
|
||||
}
|
||||
|
||||
_lastMSecs = msecs;
|
||||
_lastNSecs = nsecs;
|
||||
_clockseq = clockseq;
|
||||
|
||||
// Per 4.1.4 - Convert from unix epoch to Gregorian epoch
|
||||
msecs += 12219292800000;
|
||||
|
||||
// `time_low`
|
||||
var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
|
||||
b[i++] = tl >>> 24 & 0xff;
|
||||
b[i++] = tl >>> 16 & 0xff;
|
||||
b[i++] = tl >>> 8 & 0xff;
|
||||
b[i++] = tl & 0xff;
|
||||
|
||||
// `time_mid`
|
||||
var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
|
||||
b[i++] = tmh >>> 8 & 0xff;
|
||||
b[i++] = tmh & 0xff;
|
||||
|
||||
// `time_high_and_version`
|
||||
b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
|
||||
b[i++] = tmh >>> 16 & 0xff;
|
||||
|
||||
// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
|
||||
b[i++] = clockseq >>> 8 | 0x80;
|
||||
|
||||
// `clock_seq_low`
|
||||
b[i++] = clockseq & 0xff;
|
||||
|
||||
// `node`
|
||||
var node = options.node || _nodeId;
|
||||
for (var n = 0; n < 6; n++) {
|
||||
b[i + n] = node[n];
|
||||
}
|
||||
|
||||
return buf ? buf : unparse(b);
|
||||
}
|
||||
|
||||
// **`v4()` - Generate random UUID**
|
||||
|
||||
// See https://github.com/broofa/node-uuid for API details
|
||||
function v4(options, buf, offset) {
|
||||
// Deprecated - 'format' argument, as supported in v1.2
|
||||
var i = buf && offset || 0;
|
||||
|
||||
if (typeof(options) === 'string') {
|
||||
buf = (options === 'binary') ? new BufferClass(16) : null;
|
||||
options = null;
|
||||
}
|
||||
options = options || {};
|
||||
|
||||
var rnds = options.random || (options.rng || _rng)();
|
||||
|
||||
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
|
||||
rnds[6] = (rnds[6] & 0x0f) | 0x40;
|
||||
rnds[8] = (rnds[8] & 0x3f) | 0x80;
|
||||
|
||||
// Copy bytes to buffer, if provided
|
||||
if (buf) {
|
||||
for (var ii = 0; ii < 16; ii++) {
|
||||
buf[i + ii] = rnds[ii];
|
||||
}
|
||||
}
|
||||
|
||||
return buf || unparse(rnds);
|
||||
}
|
||||
|
||||
// Export public API
|
||||
var uuid = v4;
|
||||
uuid.v1 = v1;
|
||||
uuid.v4 = v4;
|
||||
uuid.parse = parse;
|
||||
uuid.unparse = unparse;
|
||||
uuid.BufferClass = BufferClass;
|
||||
uuid._rng = _rng;
|
||||
uuid._mathRNG = _mathRNG;
|
||||
uuid._nodeRNG = _nodeRNG;
|
||||
uuid._whatwgRNG = _whatwgRNG;
|
||||
|
||||
|
||||
if (('undefined' !== typeof module) && module.exports) {
|
||||
// Publish as node.js module
|
||||
module.exports = uuid;
|
||||
} else if (typeof define === 'function' && define.amd) {
|
||||
// Publish as AMD module
|
||||
define(function() { return uuid; });
|
||||
} else {
|
||||
// Publish as global (in browsers)
|
||||
_previousRoot = _window.uuid;
|
||||
|
||||
// **`noConflict()` - (browser only) to reset global 'uuid' var**
|
||||
uuid.noConflict = function() {
|
||||
_window.uuid = _previousRoot;
|
||||
return uuid;
|
||||
};
|
||||
|
||||
_window.uuid = uuid;
|
||||
}
|
||||
})('undefined' !== typeof window ? window : null);
|
||||
Reference in New Issue
Block a user