Skip to content

Commit

Permalink
初始化仓库
Browse files Browse the repository at this point in the history
  • Loading branch information
shaodahong committed Oct 8, 2018
0 parents commit c50479b
Show file tree
Hide file tree
Showing 9 changed files with 395 additions and 0 deletions.
25 changes: 25 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# editorconfig.org
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

[src/**]
indent_style = space
indent_size = 2

[.babelrc]
indent_style = space
indent_size = 2

[build/**]
indent_style = space
indent_size = 2
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.idea
.sass-cache
*.bak
*.log
node_modules
.DS_Store
dist
.vscode
5 changes: 5 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import AS from './lib/as'
import http from './lib/http'
import WX from './lib/wx'

export { AS, http, WX }
25 changes: 25 additions & 0 deletions lib/as.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import qs from 'qs'

async function AS(data = {}) {
if (typeof data.eventContent === 'object') {
let params = []
Object.entries(data.eventContent).forEach(([key, value]) => {
params.push(`${key}=${value}`)
})
data.eventContent = `{${params.join(',')}}`
}

// 防止 GC 掉用变量存储
const random = 'img_' + Math.random()
const img = new Image()
window[random] = img
img.onload = img.onerror = () => {
window[random] = null
}

const currentOrigin = window.location.origin
// 可以利用 qs 来格式化参数
img.src = currentOrigin + '/log.gif?' + qs.stringify(data)
}

export default AS
100 changes: 100 additions & 0 deletions lib/http.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import axios from 'axios'
import { clearToken, toLogin } from './token'

// type an error
function HttpError(message, data) {
this.msg = message
this.name = 'HttpError'
this.data = data ? (data?.data ? data.data : data) : null
this.code = data?.resCode || 0
}
HttpError.prototype = new Error()
HttpError.prototype.constructor = HttpError

const config = {
production: '/',
development: 'proxy',
test: '/'
}

/**
* 获取config配置中的请求前置路径
*/
const baseURL = config[process.env.PACKAGE]
? config[process.env.PACKAGE]
: config['development']

/**
* 配置axios
*/
const http = axios.create({
baseURL,
headers: {
Accept: 'application/json;version=3.0;compress=false',
'Content-Type': 'application/json;charset=utf-8'
},
data: {}
})

/**
* 请求拦截器,在发起请求之前
*/
http.interceptors.request.use(config => {
if (config.method === 'get') {
if (typeof config.params !== 'object') {
config.params = {}
}

config.params.requestId = Number(new Date())
}

if (Object.keys(config.data).length > 0) {
config.data.requestId = Number(new Date())
}

return config
})

/**
* 接口响应拦截器,在接口响应之后
*/
http.interceptors.response.use(
config => {
// 响应正常
if (config.data.resCode === '000000') {
return config.data.data
}
// 需要登录(没登录或登录过期)
else if (config.data.resCode === '200008') {
clearToken()
toLogin()
return false
}
// 需要绑定
else if (config.data.resCode === '200101') {
toLogin({
isBind: true
})
return false
}

// 判断微信
if (
config.data.appId &&
config.data.nonceStr &&
config.data.signature &&
config.data.timestamp
) {
return config.data
}

// reject错误处理
return Promise.reject(new HttpError(config.data.resMsg, config.data))
},
error => {
// reject错误处理
return Promise.reject(new HttpError('系统错误'))
}
)

export default http
113 changes: 113 additions & 0 deletions lib/token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import qs from 'qs'
import at from 'at-js-sdk'

const token = '_app_token_'
const openId = '_app_openId_'
const unionId = '_app_unionId_'
const virtualNo = '_app_virtualNo_'
const memNo = '_app_memNo_'

const ls = window.localStorage
const ss = window.sessionStorage

// token的操作方法
const getToken = e => ls.getItem(token)
const setToken = e => ls.setItem(token, e)
const clearToken = e => ls.removeItem(token)

// openId 操作方法
const getOpenId = e => ss.getItem(openId)
const setOpenId = e => ss.setItem(openId, e)
const clearOpenId = e => ss.removeItem(openId)

// unionId 操作方法
const getUnionId = e => ss.getItem(unionId)
const setUnionId = e => ss.setItem(unionId, e)
const clearUnionId = e => ss.removeItem(unionId)

// virtualNo 操作方法
const getVirtualNo = e => ss.getItem(virtualNo)
const setVirtualNo = e => ss.setItem(virtualNo, e)
const clearVirtualNo = e => ss.removeItem(virtualNo)

// memNo 操作方法
const getMemNo = e => ss.getItem(memNo)
const setMemNo = e => ss.setItem(memNo, e)
const clearMemNo = e => ss.removeItem(memNo)

/**
* 初始化token
* @returns {Promise<any>} resolve: 成功 reject: 失败
*/
const initToken = async e => {
return new Promise((resolve, reject) => {
if (window.isApp) {
at.getToken({
callback(res) {
if (res.token && String(res.token).length > 20) {
setToken(res.token)
resolve()
} else {
clearToken()
reject(new Error('token is empty'))
}
}
})
} else {
const token = getToken()
if (token && String(token).length > 20) {
resolve()
} else {
clearToken()
reject(new Error('token is empty'))
}
}
})
}

/**
* 跳转到登录页面
* app: 打开原生登录模块
* h5: 跳转到通用登录页面
*/
const toLogin = params => {
if (window.isApp) {
at.openLogin({
success(res) {
setToken(res.token)
window.location.reload()
},
cancel() {
clearToken()
at.closeWindow()
}
})
} else {
clearToken()
const search = {
redirect: window.location.href
}
params && Object.assign(search, params)
window.location.href = '/m/login/?' + qs.stringify(search)
}
}

export {
getToken,
setToken,
clearToken,
initToken,
toLogin,
getOpenId,
setOpenId,
clearOpenId,
getUnionId,
setUnionId,
clearUnionId,
getVirtualNo,
setVirtualNo,
clearVirtualNo,
getMemNo,
setMemNo,
clearMemNo
}
67 changes: 67 additions & 0 deletions lib/wx.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import http from './http'
import wx from 'weixin-js-sdk'

const WX = {
share: async () => {
if (!window.isWX) {
return
}

try {
// 获取微信 sdk 初始化参数
const res = await _getTicket()
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
signature: res.signature,
appId: res.appId,
timestamp: res.timestamp,
nonceStr: res.nonceStr,
jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage']
})

wx.ready(() => {
const currentOrigin = window.location.origin
const protocol = window.location.protocol
let shareLink =
`${currentOrigin}/weixinauth/authorize?type=base&redirectUri=` +
encodeURIComponent(config.url || `${currentOrigin}/m/index`)
const shareImg =
config.sharePicUrl ||
`${protocol}//carphoto.aotuzuche.com/web/auto/assets/imgs/logo.png`

const result = {
title: config.shareTitle || '凹凸租车', // 分享标题
link: shareLink, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: shareImg // 分享图标
}

// 分享给朋友
wx.onMenuShareAppMessage(
Object.assign(result, { desc: config.text || '凹凸租车' })
)

// 分享到朋友圈
wx.onMenuShareTimeline(result)
})

wx.error(res => {
console.log('wx-error', res)
})
} catch (e) {
console.log('wx-share:error', e)
}
}
}

async function _getTicket() {
const _url = encodeURIComponent(window.location.href.split('#')[0])

const result = await http.request({
method: 'get',
url: `/wechatgw/jsapi/ticket?url=${_url}`
})

return result
}

export default WX
14 changes: 14 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "auto-lib",
"version": "0.0.1",
"description": "凹凸 公用组件",
"main": "index.js",
"repository": "[email protected]:shaodahong/auto-lib.git",
"author": "shaodahong <[email protected]>",
"license": "MIT",
"dependencies": {
"axios": "^0.18.0",
"qs": "^6.5.2",
"weixin-js-sdk": "^1.4.0-test"
}
}
Loading

0 comments on commit c50479b

Please sign in to comment.