Parcourir la source

project format code

charblus il y a 5 ans
Parent
commit
17bad07cd3

+ 1 - 1
package.json

@@ -21,7 +21,7 @@
     "dev": "node build/dev-server.js wx",
     "start": "npm run dev",
     "build": "node build/build.js wx",
-    "lint": "eslint --fix --ext .js,.vue src"
+    "lint": "eslint --fix --ext .js,.vue src server/controllers"
   },
   "dependencies": {
     "mpvue": "^2.0.0",

+ 8 - 7
server/config.js

@@ -1,22 +1,23 @@
+// 相关配置上传github已删除;运行请自行添加 ,参考 README.md
 const CONF = {
     serverHost: 'localhost',
     tunnelServerUrl: '',
-    tunnelSignatureKey: '27fb7d1c161b7ca52d73cce0f1d833f9f5b5ec89',
+    tunnelSignatureKey: '',
     // 腾讯云相关配置可以查看云 API 密钥控制台:https://console.cloud.tencent.com/capi
-    qcloudAppId: '1253858020',
-    qcloudSecretId: 'AKIDve8qJWnBerpdHhbTpwnQo21kDRQ9OqRq',
-    qcloudSecretKey: 'JOEtJVWQ6XjgR4TluoTs5C3f1JCpDLEt',
-    wxMessageToken: 'weixinmsgtoken',
+    qcloudAppId: '',
+    qcloudSecretId: '',
+    qcloudSecretKey: '',
+    wxMessageToken: '',
     networkTimeout: 30000,
 
     port: '5757',
     rootPathname: '',
 
     // 微信小程序 App ID
-    appId: 'wxa28c90f932b1fb61',
+    appId: '',
 
     // 微信小程序 App Secret
-    appSecret: '64520465c87eab44d8c918a6ead2b33c',
+    appSecret: '',
 
     // 是否使用腾讯云代理登录小程序
     useQcloudLogin: false,

+ 6 - 6
server/controllers/bookdetail.js

@@ -3,10 +3,10 @@ const {mysql} = require('../qcloud')
 module.exports = async (ctx) => {
   const {id} = ctx.request.query
   const detail = await mysql('books')
-                       .select('books.*', 'cSessionInfo.user_info')
-                       .join('cSessionInfo', 'books.openid', 'cSessionInfo.open_id')
-                       .where('id', id)
-                       .first()
+    .select('books.*', 'cSessionInfo.user_info')
+    .join('cSessionInfo', 'books.openid', 'cSessionInfo.open_id')
+    .where('id', id)
+    .first()
 
   // console.log(detail)
   const info = JSON.parse(detail.user_info)
@@ -21,6 +21,6 @@ module.exports = async (ctx) => {
 
   // 浏览量+1
   await mysql('books')
-          .where('id', id)
-          .increment('count', 1)
+    .where('id', id)
+    .increment('count', 1)
 }

+ 5 - 5
server/controllers/booklist.js

@@ -3,16 +3,16 @@ const { mysql } = require('../qcloud')
 module.exports = async (ctx) => {
   const {page, openid} = ctx.request.query
   const size = 10
-  const mysqlSelect =  mysql('books')
-                      .select('books.*', 'cSessionInfo.user_info')
-                      .join('cSessionInfo', 'books.openid', 'cSessionInfo.open_id')
-                      .orderBy('books.id', 'desc')
+  const mysqlSelect = mysql('books')
+    .select('books.*', 'cSessionInfo.user_info')
+    .join('cSessionInfo', 'books.openid', 'cSessionInfo.open_id')
+    .orderBy('books.id', 'desc')
   let books
   if (openid) {
     // 根据opid过滤
     books = await mysqlSelect.where('books.openid', openid)
   } else {
-     // 全部图书 分页
+    // 全部图书 分页
     books = await mysqlSelect.limit(size).offset(Number(page) * size)
   }
   ctx.state.data = {

+ 2 - 3
server/controllers/commentlist.js

@@ -3,8 +3,8 @@ const { mysql } = require('../qcloud')
 module.exports = async (ctx) => {
   const {bookid, openid} = ctx.request.query
   const mysqlSelect = mysql('comments')
-                    .select('comments.*', 'cSessionInfo.user_info')
-                    .join('cSessionInfo', 'comments.openid', 'cSessionInfo.open_id')
+    .select('comments.*', 'cSessionInfo.user_info')
+    .join('cSessionInfo', 'comments.openid', 'cSessionInfo.open_id')
   let comments
   if (bookid) {
     // 图书详情的评论列表
@@ -24,4 +24,3 @@ module.exports = async (ctx) => {
     })
   }
 }
-

+ 14 - 14
server/controllers/index.js

@@ -6,24 +6,24 @@ const path = require('path')
  * 映射 d 文件夹下的文件为模块
  */
 const mapDir = d => {
-    const tree = {}
+  const tree = {}
 
-    // 获得当前文件夹下的所有的文件夹和文件
-    const [dirs, files] = _(fs.readdirSync(d)).partition(p => fs.statSync(path.join(d, p)).isDirectory())
+  // 获得当前文件夹下的所有的文件夹和文件
+  const [dirs, files] = _(fs.readdirSync(d)).partition(p => fs.statSync(path.join(d, p)).isDirectory())
 
-    // 映射文件夹
-    dirs.forEach(dir => {
-        tree[dir] = mapDir(path.join(d, dir))
-    })
+  // 映射文件夹
+  dirs.forEach(dir => {
+    tree[dir] = mapDir(path.join(d, dir))
+  })
 
-    // 映射文件
-    files.forEach(file => {
-        if (path.extname(file) === '.js') {
-            tree[path.basename(file, '.js')] = require(path.join(d, file))
-        }
-    })
+  // 映射文件
+  files.forEach(file => {
+    if (path.extname(file) === '.js') {
+      tree[path.basename(file, '.js')] = require(path.join(d, file))
+    }
+  })
 
-    return tree
+  return tree
 }
 
 // 默认导出当前文件夹下的映射

+ 7 - 7
server/controllers/login.js

@@ -1,10 +1,10 @@
 // 登录授权接口
 module.exports = async (ctx, next) => {
-    // 通过 Koa 中间件进行登录之后
-    // 登录信息会被存储到 ctx.state.$wxInfo
-    // 具体查看:
-    if (ctx.state.$wxInfo.loginState) {
-        ctx.state.data = ctx.state.$wxInfo.userinfo
-        ctx.state.data['time'] = Math.floor(Date.now() / 1000)
-    }
+  // 通过 Koa 中间件进行登录之后
+  // 登录信息会被存储到 ctx.state.$wxInfo
+  // 具体查看:
+  if (ctx.state.$wxInfo.loginState) {
+    ctx.state.data = ctx.state.$wxInfo.userinfo
+    ctx.state.data['time'] = Math.floor(Date.now() / 1000)
+  }
 }

+ 11 - 11
server/controllers/message.js

@@ -4,26 +4,26 @@ const { message: { checkSignature } } = require('../qcloud')
  * 响应 GET 请求(响应微信配置时的签名检查请求)
  */
 async function get (ctx, next) {
-    const { signature, timestamp, nonce, echostr } = ctx.query
-    if (checkSignature(signature, timestamp, nonce)) ctx.body = echostr
-    else ctx.body = 'ERR_WHEN_CHECK_SIGNATURE'
+  const { signature, timestamp, nonce, echostr } = ctx.query
+  if (checkSignature(signature, timestamp, nonce)) ctx.body = echostr
+  else ctx.body = 'ERR_WHEN_CHECK_SIGNATURE'
 }
 
 async function post (ctx, next) {
-    // 检查签名,确认是微信发出的请求
-    const { signature, timestamp, nonce } = ctx.query
-    if (!checkSignature(signature, timestamp, nonce)) ctx.body = 'ERR_WHEN_CHECK_SIGNATURE'
+  // 检查签名,确认是微信发出的请求
+  const { signature, timestamp, nonce } = ctx.query
+  if (!checkSignature(signature, timestamp, nonce)) ctx.body = 'ERR_WHEN_CHECK_SIGNATURE'
 
-    /**
+  /**
      * 解析微信发送过来的请求体
      * 可查看微信文档:https://mp.weixin.qq.com/debug/wxadoc/dev/api/custommsg/receive.html#接收消息和事件
      */
-    const body = ctx.request.body
+  // const body = ctx.request.body
 
-    ctx.body = 'success'
+  ctx.body = 'success'
 }
 
 module.exports = {
-    post,
-    get
+  post,
+  get
 }

+ 3 - 3
server/controllers/top.js

@@ -2,9 +2,9 @@ const {mysql} = require('../qcloud')
 
 module.exports = async (ctx) => {
   const top = await mysql('books')
-          .select('id', 'title', 'image', 'count')
-          .orderBy('count', 'desc')
-          .limit(9)
+    .select('id', 'title', 'image', 'count')
+    .orderBy('count', 'desc')
+    .limit(9)
   ctx.state.data = {
     list: top
   }

+ 0 - 156
server/controllers/tunnel.js

@@ -1,156 +0,0 @@
-const { tunnel } = require('../qcloud')
-const debug = require('debug')('koa-weapp-demo')
-
-/**
- * 这里实现一个简单的聊天室
- * userMap 为 tunnelId 和 用户信息的映射
- * 实际使用请使用数据库存储
- */
-const userMap = {}
-
-// 保存 当前已连接的 WebSocket 信道ID列表
-const connectedTunnelIds = []
-
-/**
- * 调用 tunnel.broadcast() 进行广播
- * @param  {String} type    消息类型
- * @param  {String} content 消息内容
- */
-const $broadcast = (type, content) => {
-    tunnel.broadcast(connectedTunnelIds, type, content)
-        .then(result => {
-            const invalidTunnelIds = result.data && result.data.invalidTunnelIds || []
-
-            if (invalidTunnelIds.length) {
-                console.log('检测到无效的信道 IDs =>', invalidTunnelIds)
-
-                // 从 userMap 和 connectedTunnelIds 中将无效的信道记录移除
-                invalidTunnelIds.forEach(tunnelId => {
-                    delete userMap[tunnelId]
-
-                    const index = connectedTunnelIds.indexOf(tunnelId)
-                    if (~index) {
-                        connectedTunnelIds.splice(index, 1)
-                    }
-                })
-            }
-        })
-}
-
-/**
- * 调用 TunnelService.closeTunnel() 关闭信道
- * @param  {String} tunnelId 信道ID
- */
-const $close = (tunnelId) => {
-    tunnel.closeTunnel(tunnelId)
-}
-
-/**
- * 实现 onConnect 方法
- * 在客户端成功连接 WebSocket 信道服务之后会调用该方法,
- * 此时通知所有其它在线的用户当前总人数以及刚加入的用户是谁
- */
-function onConnect (tunnelId) {
-    console.log(`[onConnect] =>`, { tunnelId })
-
-    if (tunnelId in userMap) {
-        connectedTunnelIds.push(tunnelId)
-
-        $broadcast('people', {
-            'total': connectedTunnelIds.length,
-            'enter': userMap[tunnelId]
-        })
-    } else {
-        console.log(`Unknown tunnelId(${tunnelId}) was connectd, close it`)
-        $close(tunnelId)
-    }
-}
-
-/**
- * 实现 onMessage 方法
- * 客户端推送消息到 WebSocket 信道服务器上后,会调用该方法,此时可以处理信道的消息。
- * 在本示例,我们处理 `speak` 类型的消息,该消息表示有用户发言。
- * 我们把这个发言的信息广播到所有在线的 WebSocket 信道上
- */
-function onMessage (tunnelId, type, content) {
-    console.log(`[onMessage] =>`, { tunnelId, type, content })
-
-    switch (type) {
-        case 'speak':
-            if (tunnelId in userMap) {
-                $broadcast('speak', {
-                    'who': userMap[tunnelId],
-                    'word': content.word
-                })
-            } else {
-                $close(tunnelId)
-            }
-            break
-
-        default:
-            break
-    }
-}
-
-/**
- * 实现 onClose 方法
- * 客户端关闭 WebSocket 信道或者被信道服务器判断为已断开后,
- * 会调用该方法,此时可以进行清理及通知操作
- */
-function onClose (tunnelId) {
-    console.log(`[onClose] =>`, { tunnelId })
-
-    if (!(tunnelId in userMap)) {
-        console.log(`[onClose][Invalid TunnelId]=>`, tunnelId)
-        $close(tunnelId)
-        return
-    }
-
-    const leaveUser = userMap[tunnelId]
-    delete userMap[tunnelId]
-
-    const index = connectedTunnelIds.indexOf(tunnelId)
-    if (~index) {
-        connectedTunnelIds.splice(index, 1)
-    }
-
-    // 聊天室没有人了(即无信道ID)不再需要广播消息
-    if (connectedTunnelIds.length > 0) {
-        $broadcast('people', {
-            'total': connectedTunnelIds.length,
-            'leave': leaveUser
-        })
-    }
-}
-
-module.exports = {
-    // 小程序请求 websocket 地址
-    get: async ctx => {
-        const data = await tunnel.getTunnelUrl(ctx.req)
-        const tunnelInfo = data.tunnel
-
-        userMap[tunnelInfo.tunnelId] = data.userinfo
-
-        ctx.state.data = tunnelInfo
-    },
-
-    // 信道将信息传输过来的时候
-    post: async ctx => {
-        const packet = await tunnel.onTunnelMessage(ctx.request.body)
-
-        debug('Tunnel recive a package: %o', packet)
-
-        switch (packet.type) {
-            case 'connect':
-                onConnect(packet.tunnelId)
-                break
-            case 'message':
-                onMessage(packet.tunnelId, packet.content.messageType, packet.content.messageContent)
-                break
-            case 'close':
-                onClose(packet.tunnelId)
-                break
-        }
-    }
-
-}

+ 4 - 4
server/controllers/upload.js

@@ -1,9 +1,9 @@
 const { uploader } = require('../qcloud')
 
 module.exports = async ctx => {
-    // 获取上传之后的结果
-    // 具体可以查看:
-    const data = await uploader(ctx.req)
+  // 获取上传之后的结果
+  // 具体可以查看:
+  const data = await uploader(ctx.req)
 
-    ctx.state.data = data
+  ctx.state.data = data
 }

+ 9 - 9
server/controllers/user.js

@@ -1,11 +1,11 @@
 module.exports = async (ctx, next) => {
-    // 通过 Koa 中间件进行登录态校验之后
-    // 登录信息会被存储到 ctx.state.$wxInfo
-    // 具体查看:
-    if (ctx.state.$wxInfo.loginState === 1) {
-        // loginState 为 1,登录态校验成功
-        ctx.state.data = ctx.state.$wxInfo.userinfo
-    } else {
-        ctx.state.code = -1
-    }
+  // 通过 Koa 中间件进行登录态校验之后
+  // 登录信息会被存储到 ctx.state.$wxInfo
+  // 具体查看:
+  if (ctx.state.$wxInfo.loginState === 1) {
+    // loginState 为 1,登录态校验成功
+    ctx.state.data = ctx.state.$wxInfo.userinfo
+  } else {
+    ctx.state.code = -1
+  }
 }

+ 4 - 4
server/routes/index.js

@@ -21,10 +21,10 @@ router.get('/user', validationMiddleware, controllers.user)
 router.post('/upload', controllers.upload)
 
 // --- 信道服务接口 Demo --- //
-// GET  用来响应请求信道地址的
-router.get('/tunnel', controllers.tunnel.get)
-// POST 用来处理信道传递过来的消息
-router.post('/tunnel', controllers.tunnel.post)
+// // GET  用来响应请求信道地址的
+// router.get('/tunnel', controllers.tunnel.get)
+// // POST 用来处理信道传递过来的消息
+// router.post('/tunnel', controllers.tunnel.post)
 
 // --- 客服消息接口 Demo --- //
 // GET  用来响应小程序后台配置时发送的验证请求

+ 1 - 1
src/App.vue

@@ -1,6 +1,6 @@
 
 <script>
-import qcloud from 'wafer2-client-sdk'
+// import qcloud from 'wafer2-client-sdk'
 export default {
   async created () {
     // const res = await get('/weapp/demo')

+ 2 - 2
src/components/BookInfo.vue

@@ -50,8 +50,8 @@ export default {
   },
   props: ['info'],
   computed: {
-    userinfo() {
-      return this.info.user_info || {};
+    userinfo () {
+      return this.info.user_info || {}
     }
   }
 }

+ 2 - 2
src/components/CommentList.vue

@@ -31,8 +31,8 @@
 export default {
   props: ['comments', 'type'],
   methods: {
-    handleClick(comment) {
-      if(this.type === 'user') {
+    handleClick (comment) {
+      if (this.type === 'user') {
         wx.navigateTo({
           url: '/pages/detail/main?id=' + comment.bookid
         })

+ 11 - 11
src/pages/comments/Comment.vue

@@ -17,7 +17,7 @@ import {get} from '@/util'
 import CommentList from '@/components/CommentList'
 import Card from '@/components/Card'
 export default {
-  data() {
+  data () {
     return {
       comments: [],
       books: [],
@@ -29,14 +29,14 @@ export default {
     Card
   },
   methods: {
-    init(){
+    init () {
       wx.showNavigationBarLoading()
-      this.getComments();
-      this.getBooks();
+      this.getComments()
+      this.getBooks()
       wx.hideNavigationBarLoading()
     },
-    async getBooks() {
-      const books = await get('/weapp/booklist',{
+    async getBooks () {
+      const books = await get('/weapp/booklist', {
         openid: this.userinfo.openId
       })
       this.books = books.list
@@ -44,18 +44,18 @@ export default {
     async getComments () {
       const comments = await get('/weapp/commentlist', {
         openid: this.userinfo.openId
-      });
+      })
       this.comments = comments.list
     }
   },
-  onPullDownRefresh(){
+  onPullDownRefresh () {
     this.init()
     wx.stopPullDownRefresh()
   },
-  onShow(){
-    if(!this.userinfo.openId){
+  onShow () {
+    if (!this.userinfo.openId) {
       let userinfo = wx.getStorageSync('userInfo')
-      if(userinfo){
+      if (userinfo) {
         this.userinfo = userinfo
         this.init()
       }

+ 29 - 30
src/pages/detail/Detail.vue

@@ -48,9 +48,9 @@ export default {
   },
   computed: {
     showAdd () {
-      //未登录
-      if(!this.userinfo.openId) {
-        return false;
+      // 未登录
+      if (!this.userinfo.openId) {
+        return false
       }
       // 评论页面里查到有自己的openid
       if (this.comments.filter(v => v.openid === this.userinfo.openId).length) {
@@ -62,7 +62,7 @@ export default {
   methods: {
     async addComment () {
       if (!this.comment) {
-        return;
+        return
       }
       // 评论内容 手机型号 地理位置 图书id 用户openid
       const data = {
@@ -74,23 +74,23 @@ export default {
       }
       try {
         console.log(data)
-        await post('/weapp/addcomment', data);
-        this.comment = '';
-        this.getComments();
+        await post('/weapp/addcomment', data)
+        this.comment = ''
+        this.getComments()
       } catch (e) {
         showModal('失败', e.msg)
       }
     },
     getGeo (e) {
       // NVYWM4sZYGjaHPpO6vwVk0j1v4ijBBKB
-      const ak = 'NVYWM4sZYGjaHPpO6vwVk0j1v4ijBBKB';
-      let url = 'http://api.map.baidu.com/geocoder/v2/';
+      const ak = 'NVYWM4sZYGjaHPpO6vwVk0j1v4ijBBKB'
+      let url = 'http://api.map.baidu.com/geocoder/v2/'
 
-      if(e.target.value) {
+      if (e.target.value) {
         wx.getLocation({
           type: 'wgs84',
           success: geo => {
-            console.log('地理数据', geo);
+            console.log('地理数据', geo)
             wx.request({
               url,
               data: {
@@ -101,26 +101,25 @@ export default {
               success: res => {
                 console.log('百度api返回', res)
                 if (res.data.status === 0) {
-                  this.location = res.data.result.addressComponent.city;
+                  this.location = res.data.result.addressComponent.city
                 } else {
-                  this.location = '未知地点';
+                  this.location = '未知地点'
                 }
               }
             })
-            
           }
         })
       } else {
-        this.location = '';
+        this.location = ''
       }
     },
-    getPhone(e) {
-      if(e.target.value) {
-        const res = wx.getSystemInfoSync();
+    getPhone (e) {
+      if (e.target.value) {
+        const res = wx.getSystemInfoSync()
         // console.log(res.model);
-        this.phone = res.model;
+        this.phone = res.model
       } else {
-        this.phone = '';
+        this.phone = ''
       }
     },
     async getDetail () {
@@ -132,16 +131,16 @@ export default {
       this.info = info
     },
     async getComments () {
-      const comments = await get('/weapp/commentlist', {bookid: this.bookid});
-      console.log('comments', comments);
+      const comments = await get('/weapp/commentlist', {bookid: this.bookid})
+      console.log('comments', comments)
       this.comments = comments.list || []
     }
   },
-  onShareAppMessage: function(res) {
+  onShareAppMessage: function (res) {
     return {
       title: this.info.title,
       path: 'pages/detail/main',
-      imageUrl:'',  // 不填写默认页面截图
+      imageUrl: '' // 不填写默认页面截图
       // success: function (shareTickets) {
       //   // console.info(shareTickets + '成功');
       //   console.log(shareTickets + '成功');
@@ -156,15 +155,15 @@ export default {
       //   // 不管成功失败都会执行
       // }
     }
-	},
+  },
   mounted () {
-    this.bookid = this.$root.$mp.query.id;  // 跳转页面使用this.$root.$mp.query获取参数
-    this.getDetail();
-    this.getComments();
+    this.bookid = this.$root.$mp.query.id // 跳转页面使用this.$root.$mp.query获取参数
+    this.getDetail()
+    this.getComments()
     const userinfo = wx.getStorageSync('userInfo')
-    console.log('userInfo', userinfo);
+    console.log('userInfo', userinfo)
     if (userinfo) {
-      this.userinfo = userinfo;
+      this.userinfo = userinfo
     }
     // wx.showShareMenu({
     //   withShareTicket: true