最近包工頭喊農民工小鄭搬磚,小鄭搬完磚後沉思片刻,決定寫篇小作文分享下,作為一個初學者的全棧專案,去學習它的搭建,到落地,再到部署維護,是非常好的。

​ ------題記

寫在前面

通過本文的學習,你可以學到

  • vue2、element ui、vue-element-admin在前端的使用
  • 元件設計
  • echarts在前端中的使用
  • eggjs在後端node專案中的使用
  • docker一鍵化部署

需求分析

背景

近些年,網路詐騙案頻發,有假扮家裡茶葉滯銷的茶花女,有假扮和男朋友分手去山區支教的女教師,有告知你中了非常6+1的大獎主持人,有假扮越南那邊過來結婚的妹子,各類案件層出不窮。作為公民,我們應該在社會主義新時代下積極學習組織上宣傳反詐騙知識,提高防範意識。除此之外,對於種種詐騙案件,是網站的我們就應該封其網站,是電話的我們就應該封其電話,是銀行的我們就該封其銀行賬號,是虛擬賬號的我們就應該封其虛擬賬號。我相信,在我們的不懈努力之下,我們的社會將會更和諧更美好!

需求

長話短說,需求大致是這樣子的:有管理員、市局接警員、縣區局接警員、電話追查專員、網站追查專員、銀行追查專員、虛擬賬號專員這幾類角色, 相關的角色可以進入相關的頁面進行相關的操作,其中市局和管理員的警情錄入是不需要稽核,直接派單下去,而縣區局的警情錄入需要進行稽核。當稽核通過後,會進行相應的派單。各類追查員將結果反饋給該警單。系統管理員這邊還可以進行人員、機構、警情類別,銀行卡、資料統計、匯出等功能。希望是越快越好,越簡單越好,領導要看的。

部分效果如圖:

技術預研

這個專案不是很大,複雜度也不是很高,併發量也不會太大,畢竟是部署在public police network下的。所以我這邊選用vue2,結合花褲衩大佬的vue-element-admin,前端這邊就差不多了,後端這邊用的是阿里開源的eggjs,因為它使用起來很方便。資料庫用的是mysql。部署這邊提供了兩套方案,一套是傳統的nginx、mysql、node、一個一個單獨安裝配置。另一種是docker部署的方式。

功能實現

前端

vue程式碼規範

參見:https://www.yuque.com/ng46ql/tynary

vue工程目錄結構

參見:https://panjiachen.gitee.io/vue-element-admin-site/zh/guide/#目錄結構

vue元件設計與封裝

這裡我選了幾個有代表性的典型的元件來講解,我們先來看一張圖找找元件設計和封裝的感覺。

通過觀察我們發現,在後臺管理介面中,蠻多的頁面是長這樣子的,我們不可能來一個頁面我們就再寫一次佈局,這樣人都要搞沒掉。所以我們會有想法地把它封裝成一個container.vue,它主要包含頭部的標題和右邊的新增按鈕、中間的過濾面板以及下方的表格。

container.vue是一個佈局元件,它主要是框定了你一個頁面大致的佈局, 在適當的位置,我們加入插槽slot去表示這塊未知的區域,container.vue程式碼實現如下:

  1. <template>
  2. <div>
  3. <el-row class="top">
  4. <el-col :span="24">
  5. <el-row>
  6. <el-col :span="12">
  7. <div
  8. v-if="title"
  9. class="title"
  10. >
  11. {{ title }}
  12. </div>
  13. </el-col>
  14. <el-col
  15. :span="12"
  16. class="btn-group"
  17. >
  18. <slot name="topExtra" />
  19. <el-col />
  20. </el-col>
  21. </el-row>
  22. </el-col>
  23. <el-col :span="24">
  24. <slot name="tab" />
  25. </el-col>
  26. </el-row>
  27. <div class="content">
  28. <slot name="content" />
  29. </div>
  30. </div>
  31. </template>
  32. <script>
  33. export default {
  34. name: 'CommonContainer',
  35. props: {
  36. title: { type: String, default: '' }
  37. }
  38. }
  39. </script>
  40. <style lang="scss" scoped>
  41. .top {
  42. padding: 15px;
  43. min-height: 100px;
  44. background-color: #fff;
  45. box-shadow: 0 3px 5px -3px rgba(0, 0, 0, 0.1);
  46. }
  47. .title-box {
  48. height: 100px;
  49. line-height: 100px;
  50. display: flex;
  51. justify-content: space-between;
  52. align-items: center;
  53. }
  54. .title {
  55. font-size: 30px;
  56. font-weight: 700;
  57. }
  58. .content {
  59. margin: 20px 5px 0;
  60. padding: 20px 10px;
  61. background: #fff;
  62. }
  63. .btn-group {
  64. text-align: right;
  65. padding: 0 10px;
  66. }
  67. </style>

往下走,我們會想到怎麼去設計表格這個元件,在設計這個元件的時候,我們需要清楚的知道,這個元件的輸入以及輸出是什麼?比如說table-query.vue這個元件,從名字我們能夠看出,它是有查詢請求的,那麼對於請求,很容易抽象出的一些東西是,請求地址,請求引數,請求方法等等,所以這邊的props大致可以這麼敲定。

  1. props: {
  2. // 請求表格資料的url地址
  3. url: { type: String, required: true },
  4. // 預設分頁數
  5. pageSize: { type: Number, default: 10 },
  6. // 是否展示序號
  7. index: { type: Boolean, default: true },
  8. // 表格的列的結構
  9. columns: { type: Array, required: true },
  10. orgId: { type: String, required: false, default: '' },
  11. // 請求表格資料的方法
  12. method: { type: String, default: 'post' },
  13. // 請求表格資料的引數
  14. params: { type: Object, default: () => ({}) },
  15. // 是否支援高亮選中
  16. isHighlightRow: { type: Boolean, default: false },
  17. // 是否顯示分頁
  18. isShowPagination: { type: Boolean, default: true },
  19. // 是否顯示迷你分頁
  20. isPaginationSizeSmall: { type: Boolean, default: false }
  21. },

這裡的輸出,我們期望的是,當用戶點選詳情、檢視、刪除的時候,我要知道這一行的具體資料,那麼大致可以這麼敲定。

  1. handleClick(row, type, title) {
  2. this.$emit('click-action', row, type, title)
  3. },

這邊作為元件的資料通訊已經敲定了,剩下的也就是一些封裝請求的邏輯,頁面互動的邏輯,具體地可以看一下table-query.vue的實現

  1. <template>
  2. <div>
  3. <el-table
  4. ref="table"
  5. border
  6. :data="data"
  7. :loading="isLoading"
  8. :highlight-row="isHighlightRow"
  9. :row-class-name="tableRowClassName"
  10. >
  11. <template v-for="column in columns">
  12. <template v-if="column.key === 'actions'">
  13. <el-table-column
  14. :key="column.key"
  15. align="center"
  16. :width="column.width"
  17. :label="column.title"
  18. >
  19. <template slot-scope="scope">
  20. <el-button
  21. v-for="action in filterOperate(
  22. column.actions,
  23. scope.row.btnList
  24. )"
  25. :key="action.type"
  26. type="text"
  27. size="small"
  28. @click="handleClick(scope.row, action.type, action.title)"
  29. >{{ action.title }}</el-button>
  30. </template>
  31. </el-table-column>
  32. </template>
  33. <template v-else-if="column.key === 'NO'">
  34. <el-table-column
  35. :key="column.key"
  36. type="index"
  37. width="80"
  38. align="center"
  39. :label="column.title"
  40. />
  41. </template>
  42. <template v-else>
  43. <el-table-column
  44. :key="column.key"
  45. align="center"
  46. :prop="column.key"
  47. :width="column.width"
  48. :label="column.title"
  49. :formatter="column.formatter"
  50. :show-overflow-tooltip="true"
  51. />
  52. </template>
  53. </template>
  54. </el-table>
  55. <el-row type="flex" justify="center" style="margin-top: 10px;">
  56. <el-col :span="24">
  57. <el-pagination
  58. v-if="isShowPagination"
  59. :small="true"
  60. :total="total"
  61. :background="true"
  62. :page-sizes="pageSizeOptions"
  63. :current-page="pagination.page"
  64. :page-size="pagination.pageSize"
  65. @current-change="changePage"
  66. @size-change="changePageSize"
  67. />
  68. </el-col>
  69. </el-row>
  70. </div>
  71. </template>
  72. <script>
  73. import request from '@/utils/request'
  74. import { getLength } from '@/utils/tools'
  75. export default {
  76. name: 'CommonTableQuery',
  77. props: {
  78. // 請求表格資料的url地址
  79. url: { type: String, required: true },
  80. // 預設分頁數
  81. pageSize: { type: Number, default: 10 },
  82. // 是否展示序號
  83. index: { type: Boolean, default: true },
  84. // 表格的列的結構
  85. columns: { type: Array, required: true },
  86. orgId: { type: String, required: false, default: '' },
  87. // 請求表格資料的方法
  88. method: { type: String, default: 'post' },
  89. // 請求表格資料的引數
  90. params: { type: Object, default: () => ({}) },
  91. // 是否支援高亮選中
  92. isHighlightRow: { type: Boolean, default: false },
  93. // 是否顯示分頁
  94. isShowPagination: { type: Boolean, default: true },
  95. // 是否顯示迷你分頁
  96. isPaginationSizeSmall: { type: Boolean, default: false }
  97. },
  98. data() {
  99. return {
  100. // 表格的行
  101. data: [],
  102. // 分頁總數
  103. total: 0,
  104. // 表格資料是否載入
  105. isLoading: false,
  106. // 是否全選
  107. isSelectAll: false,
  108. // 渲染後的列資料欄位
  109. renderColumns: [],
  110. // 分頁
  111. pagination: {
  112. page: 1,
  113. pageSize: this.pageSize
  114. }
  115. }
  116. },
  117. computed: {
  118. // 是否有資料
  119. hasData() {
  120. return getLength(this.data) > 0
  121. },
  122. // 分頁條數
  123. pageSizeOptions() {
  124. return this.isPaginationSizeSmall ? [10, 20, 30] : [10, 20, 30, 50, 100]
  125. }
  126. },
  127. created() {
  128. this.getTableData()
  129. },
  130. methods: {
  131. tableRowClassName({ row, rowIndex }) {
  132. // if (rowIndex === 1) {
  133. // return 'warning-row'
  134. // } else if (rowIndex === 3) {
  135. // return 'success-row'
  136. // }
  137. if (row.alarmNo && row.alarmNo.startsWith('FZYG')) {
  138. return 'warning-row'
  139. }
  140. return ''
  141. },
  142. // 改變分頁
  143. changePage(page) {
  144. this.pagination.page = page
  145. this.getTableData()
  146. },
  147. // 改變分頁大小
  148. changePageSize(pageSize) {
  149. this.pagination.pageSize = pageSize
  150. this.getTableData()
  151. },
  152. // 獲取表格的資料
  153. getTableData() {
  154. if (!this.url) {
  155. return
  156. }
  157. const {
  158. url,
  159. params,
  160. orgId,
  161. pagination: { page, pageSize },
  162. isShowPagination,
  163. method
  164. } = this
  165. this.isLoading = true
  166. this.isSelectAll = false
  167. const parameter = isShowPagination
  168. ? { page, pageSize, orgId, ...params }
  169. : { orgId, ...params }
  170. request({
  171. method,
  172. url,
  173. [method === 'post' ? 'data' : 'params']: parameter
  174. })
  175. .then(res => {
  176. const {
  177. data: { list = [], total, page, pageSize }
  178. } = res || {}
  179. this.isLoading = false
  180. this.data = list
  181. if (this.isShowPagination) {
  182. this.total = total === null ? 0 : total
  183. this.pagination = {
  184. page,
  185. pageSize
  186. }
  187. }
  188. })
  189. .catch(err => {
  190. this.isLoading = false
  191. console.log(err)
  192. })
  193. },
  194. // 手動擋分頁查詢
  195. query(page = 1, pageSize = 10) {
  196. this.pagination = { page, pageSize }
  197. this.getTableData()
  198. },
  199. handleClick(row, type, title) {
  200. this.$emit('click-action', row, type, title)
  201. },
  202. filterOperate(actions, btnList) {
  203. return actions.filter(action => btnList.includes(action.type))
  204. }
  205. }
  206. }
  207. </script>
  208. <style>
  209. .el-table .warning-row {
  210. background: oldlace;
  211. }
  212. .el-table .success-row {
  213. background: #f0f9eb;
  214. }
  215. .el-tooltip__popper {
  216. max-width: 80%;
  217. }
  218. .el-tooltip__popper,
  219. .el-tooltip__popper.is-dark {
  220. background: #f5f5f5 !important;
  221. color: #303133 !important;
  222. }
  223. </style>

element-table: https://element.eleme.cn/#/zh-CN/component/table

element-pagination: https://element.eleme.cn/#/zh-CN/component/pagination

檔案上傳與下載,這個是點開警情、追查的相關頁面進去的功能,大體上和樓上的表格類似,就是在原來的基礎上,去掉了分頁,加上了檔案上傳的元件。

“DO NOT REPEAT"原則, 我們期望的是寫一次核心程式碼就好,剩下的我們每次只需要在用到的地方引入table-file.vue 就好了,這樣子維護起來也方便,這就有個這個元件的想法。

我們還是想一下,對於檔案我們不外乎有這些操作,上傳、下載、刪除、修改、預覽等等,所以這邊元件的輸入大致可以這麼敲定。

  1. props: {
  2. canUpload: { type: Boolean, default: true },
  3. canDelete: { type: Boolean, default: true },
  4. canDownload: { type: Boolean, default: true },
  5. columns: { type: Array, default: () => [] },
  6. affix: { type: String, default: '' }
  7. },

輸出的話,跟樓上的table-query.vue差不多

  1. handleClick(row, type, title) {
  2. this.$emit('click-action', row, type, title)
  3. },

具體地可以看下table-file.vue 的實現

  1. <template>
  2. <el-row>
  3. <el-col v-if="canUpload" :span="24">
  4. <el-upload
  5. ref="upload"
  6. :action="url"
  7. drag
  8. :limit="9"
  9. name="affix"
  10. :multiple="true"
  11. :auto-upload="false"
  12. :with-credentials="true"
  13. :on-error="onError"
  14. :file-list="fileList"
  15. :on-remove="onRemove"
  16. :on-change="onChange"
  17. :on-exceed="onExceed"
  18. :on-success="onSuccess"
  19. :on-preview="onPreview"
  20. :before-upload="beforeUpload"
  21. :before-remove="beforeRemove"
  22. :on-progress="onProgress"
  23. :headers="headers"
  24. >
  25. <!-- <el-button size="small" type="primary">選擇檔案</el-button> -->
  26. <i class="el-icon-upload" />
  27. <div class="el-upload__text">將檔案拖到此處,或<em>選擇檔案</em></div>
  28. <div slot="tip" class="el-upload__tip">
  29. 檔案格式不限,一次最多隻能上傳9個檔案,單個檔案允許最大100MB
  30. </div>
  31. </el-upload>
  32. </el-col>
  33. <el-col v-if="canUpload" style="margin: 10px auto;">
  34. <el-button
  35. size="small"
  36. type="primary"
  37. @click="upload"
  38. >確認上傳</el-button>
  39. </el-col>
  40. <el-col :span="24">
  41. <el-table
  42. ref="table"
  43. border
  44. :data="data"
  45. style="width: 100%; margin: 20px auto;"
  46. >
  47. <template v-for="column in mapColumns">
  48. <template v-if="column.key === 'actions'">
  49. <el-table-column
  50. :key="column.key"
  51. align="center"
  52. :label="column.title"
  53. >
  54. <template slot-scope="scope">
  55. <el-button
  56. v-for="action in column.actions"
  57. :key="action.type"
  58. type="text"
  59. size="small"
  60. @click="handleClick(scope.row, action.type, action.title)"
  61. >{{ action.title }}</el-button>
  62. </template>
  63. </el-table-column>
  64. </template>
  65. <template v-else-if="column.key === 'NO'">
  66. <el-table-column
  67. :key="column.key"
  68. type="index"
  69. width="80"
  70. align="center"
  71. :label="column.title"
  72. />
  73. </template>
  74. <template v-else>
  75. <el-table-column
  76. :key="column.key"
  77. :prop="column.key"
  78. align="center"
  79. :label="column.title"
  80. />
  81. </template>
  82. </template>
  83. </el-table>
  84. </el-col>
  85. </el-row>
  86. </template>
  87. <script>
  88. import Cookies from 'js-cookie'
  89. import { getByIds } from '@/api/file'
  90. import { formatDate } from '@/utils/tools'
  91. export default {
  92. name: 'TableFile',
  93. props: {
  94. canUpload: { type: Boolean, default: true },
  95. canDelete: { type: Boolean, default: true },
  96. canDownload: { type: Boolean, default: true },
  97. columns: { type: Array, default: () => [] },
  98. affix: { type: String, default: '' }
  99. },
  100. data() {
  101. return {
  102. fileList: [],
  103. data: [],
  104. ids: [],
  105. headers: {
  106. 'x-csrf-token': Cookies.get('csrfToken')
  107. },
  108. mapColumns: [],
  109. url: process.env.VUE_APP_UPLOAD_API
  110. }
  111. },
  112. watch: {
  113. affix: {
  114. async handler(newAffix) {
  115. this.data = []
  116. this.ids = []
  117. if (newAffix) {
  118. this.ids = newAffix.split(',').map(id => Number(id))
  119. if (this.ids.length > 0) {
  120. const { data } = await getByIds({ ids: this.ids })
  121. this.data = data.map(item => {
  122. const { createTime, ...rest } = item
  123. return {
  124. createTime: formatDate(
  125. 'YYYY-MM-DD HH:mm:ss',
  126. createTime * 1000
  127. ),
  128. ...rest
  129. }
  130. })
  131. }
  132. }
  133. },
  134. immediate: true
  135. },
  136. canDelete: {
  137. handler(newVal) {
  138. if (newVal) {
  139. this.mapColumns = JSON.parse(JSON.stringify(this.columns))
  140. } else {
  141. if (this.mapColumns[this.mapColumns.length - 1]) {
  142. this.mapColumns[this.mapColumns.length - 1].actions = [
  143. {
  144. title: '下載',
  145. type: 'download'
  146. }
  147. ]
  148. }
  149. }
  150. },
  151. immediate: true
  152. }
  153. },
  154. created() {
  155. this.mapColumns = JSON.parse(JSON.stringify(this.columns))
  156. if (!this.canDelete) {
  157. if (this.mapColumns[this.mapColumns.length - 1]) {
  158. this.mapColumns[this.mapColumns.length - 1].actions = [
  159. {
  160. title: '下載',
  161. type: 'download'
  162. }
  163. ]
  164. }
  165. }
  166. },
  167. methods: {
  168. beforeUpload(file, fileList) {
  169. console.log('beforeUpload: ', file, fileList)
  170. },
  171. onSuccess(response, file, fileList) {
  172. const {
  173. data: { id, createTime, ...rest }
  174. } = response
  175. this.data.push({
  176. id,
  177. createTime: formatDate('YYYY-MM-DD HH:mm:ss', createTime * 1000),
  178. ...rest
  179. })
  180. this.ids.push(id)
  181. this.clear()
  182. },
  183. onError(err, file, fileList) {
  184. console.log(err, file, fileList)
  185. },
  186. onPreview(file, fileList) {
  187. console.log('onPreview: ', file, fileList)
  188. },
  189. beforeRemove(file, fileList) {
  190. console.log('beforeRemove: ', file, fileList)
  191. },
  192. onExceed(files, fileList) {
  193. console.log('onExceed: ', files, fileList)
  194. // this.$message.warning(`當前限制選擇 3 個檔案,本次選擇了 ${files.length} 個檔案,共選擇了 ${files.length + fileList.length} 個檔案`)
  195. },
  196. onRemove(file, fileList) {
  197. console.log('onRemove: ', file, fileList)
  198. },
  199. onChange(file, fileList) {
  200. console.log('onChange: ', file, fileList)
  201. },
  202. onProgress(file, fileList) {
  203. console.log('onProgress: ', file, fileList)
  204. },
  205. upload() {
  206. this.$refs.upload.submit()
  207. },
  208. clear() {
  209. this.$refs.upload.clearFiles()
  210. this.fileList = []
  211. },
  212. handleClick(row, type, title) {
  213. this.$emit('click-action', row, type, title)
  214. },
  215. deleteData(id) {
  216. const index = this.ids.indexOf(id)
  217. this.ids.splice(index, 1)
  218. this.data.splice(index, 1)
  219. }
  220. }
  221. }
  222. </script>
  223. <style scoped>
  224. .center {
  225. display: flex;
  226. justify-content: center;
  227. }
  228. </style>

element-upload: https://element.eleme.cn/#/zh-CN/component/upload

功能實現-檔案匯出

資料的匯出也是這種後臺管理系統比較常見的場景,這件事情可以前端做,也可以後端做。那麼在這裡結合xlsxfile-saver這兩個包,在src下新建一個excel資料夾, 然後新建一個js檔案export2Excel.js

  1. /* eslint-disable */
  2. import { saveAs } from 'file-saver'
  3. import XLSX from 'xlsx'
  4. function generateArray(table) {
  5. var out = [];
  6. var rows = table.querySelectorAll('tr');
  7. var ranges = [];
  8. for (var R = 0; R < rows.length; ++R) {
  9. var outRow = [];
  10. var row = rows[R];
  11. var columns = row.querySelectorAll('td');
  12. for (var C = 0; C < columns.length; ++C) {
  13. var cell = columns[C];
  14. var colspan = cell.getAttribute('colspan');
  15. var rowspan = cell.getAttribute('rowspan');
  16. var cellValue = cell.innerText;
  17. if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;
  18. //Skip ranges
  19. ranges.forEach(function (range) {
  20. if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
  21. for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
  22. }
  23. });
  24. //Handle Row Span
  25. if (rowspan || colspan) {
  26. rowspan = rowspan || 1;
  27. colspan = colspan || 1;
  28. ranges.push({
  29. s: {
  30. r: R,
  31. c: outRow.length
  32. },
  33. e: {
  34. r: R + rowspan - 1,
  35. c: outRow.length + colspan - 1
  36. }
  37. });
  38. };
  39. //Handle Value
  40. outRow.push(cellValue !== "" ? cellValue : null);
  41. //Handle Colspan
  42. if (colspan)
  43. for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
  44. }
  45. out.push(outRow);
  46. }
  47. return [out, ranges];
  48. };
  49. function datenum(v, date1904) {
  50. if (date1904) v += 1462;
  51. var epoch = Date.parse(v);
  52. return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
  53. }
  54. function sheet_from_array_of_arrays(data, opts) {
  55. var ws = {};
  56. var range = {
  57. s: {
  58. c: 10000000,
  59. r: 10000000
  60. },
  61. e: {
  62. c: 0,
  63. r: 0
  64. }
  65. };
  66. for (var R = 0; R != data.length; ++R) {
  67. for (var C = 0; C != data[R].length; ++C) {
  68. if (range.s.r > R) range.s.r = R;
  69. if (range.s.c > C) range.s.c = C;
  70. if (range.e.r < R) range.e.r = R;
  71. if (range.e.c < C) range.e.c = C;
  72. var cell = {
  73. v: data[R][C]
  74. };
  75. if (cell.v == null) continue;
  76. var cell_ref = XLSX.utils.encode_cell({
  77. c: C,
  78. r: R
  79. });
  80. if (typeof cell.v === 'number') cell.t = 'n';
  81. else if (typeof cell.v === 'boolean') cell.t = 'b';
  82. else if (cell.v instanceof Date) {
  83. cell.t = 'n';
  84. cell.z = XLSX.SSF._table[14];
  85. cell.v = datenum(cell.v);
  86. } else cell.t = 's';
  87. ws[cell_ref] = cell;
  88. }
  89. }
  90. if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
  91. return ws;
  92. }
  93. function Workbook() {
  94. if (!(this instanceof Workbook)) return new Workbook();
  95. this.SheetNames = [];
  96. this.Sheets = {};
  97. }
  98. function s2ab(s) {
  99. var buf = new ArrayBuffer(s.length);
  100. var view = new Uint8Array(buf);
  101. for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  102. return buf;
  103. }
  104. export function export_table_to_excel(id) {
  105. var theTable = document.getElementById(id);
  106. var oo = generateArray(theTable);
  107. var ranges = oo[1];
  108. /* original data */
  109. var data = oo[0];
  110. var ws_name = "SheetJS";
  111. var wb = new Workbook(),
  112. ws = sheet_from_array_of_arrays(data);
  113. /* add ranges to worksheet */
  114. // ws['!cols'] = ['apple', 'banan'];
  115. ws['!merges'] = ranges;
  116. /* add worksheet to workbook */
  117. wb.SheetNames.push(ws_name);
  118. wb.Sheets[ws_name] = ws;
  119. var wbout = XLSX.write(wb, {
  120. bookType: 'xlsx',
  121. bookSST: false,
  122. type: 'binary'
  123. });
  124. saveAs(new Blob([s2ab(wbout)], {
  125. type: "application/octet-stream"
  126. }), "test.xlsx")
  127. }
  128. export function export_json_to_excel({
  129. multiHeader = [],
  130. header,
  131. data,
  132. filename,
  133. merges = [],
  134. autoWidth = true,
  135. bookType = 'xlsx'
  136. } = {}) {
  137. /* original data */
  138. filename = filename || 'excel-list'
  139. data = [...data]
  140. data.unshift(header);
  141. for (let i = multiHeader.length - 1; i > -1; i--) {
  142. data.unshift(multiHeader[i])
  143. }
  144. var ws_name = "SheetJS";
  145. var wb = new Workbook(),
  146. ws = sheet_from_array_of_arrays(data);
  147. if (merges.length > 0) {
  148. if (!ws['!merges']) ws['!merges'] = [];
  149. merges.forEach(item => {
  150. ws['!merges'].push(XLSX.utils.decode_range(item))
  151. })
  152. }
  153. if (autoWidth) {
  154. /*設定worksheet每列的最大寬度*/
  155. const colWidth = data.map(row => row.map(val => {
  156. /*先判斷是否為null/undefined*/
  157. if (val == null) {
  158. return {
  159. 'wch': 10
  160. };
  161. }
  162. /*再判斷是否為中文*/
  163. else if (val.toString().charCodeAt(0) > 255) {
  164. return {
  165. 'wch': val.toString().length * 2
  166. };
  167. } else {
  168. return {
  169. 'wch': val.toString().length
  170. };
  171. }
  172. }))
  173. /*以第一行為初始值*/
  174. let result = colWidth[0];
  175. for (let i = 1; i < colWidth.length; i++) {
  176. for (let j = 0; j < colWidth[i].length; j++) {
  177. if (result[j]['wch'] < colWidth[i][j]['wch']) {
  178. result[j]['wch'] = colWidth[i][j]['wch'];
  179. }
  180. }
  181. }
  182. ws['!cols'] = result;
  183. }
  184. /* add worksheet to workbook */
  185. wb.SheetNames.push(ws_name);
  186. wb.Sheets[ws_name] = ws;
  187. var wbout = XLSX.write(wb, {
  188. bookType: bookType,
  189. bookSST: false,
  190. type: 'binary'
  191. });
  192. saveAs(new Blob([s2ab(wbout)], {
  193. type: "application/octet-stream"
  194. }), `${filename}.${bookType}`);
  195. }

邏輯程式碼如下

  1. downloadExcel() {
  2. this.$confirm('將匯出為excel檔案,確認匯出?', '提示', {
  3. confirmButtonText: '確定',
  4. cancelButtonText: '取消',
  5. type: 'warning'
  6. })
  7. .then(() => {
  8. this.export2Excel()
  9. })
  10. .catch((e) => {
  11. this.$Message.error(e);
  12. })
  13. },
  14. // 資料寫入excel
  15. export2Excel() {
  16. import('@/excel/export2Excel').then(excel => {
  17. const tHeader = [
  18. '警情編號',
  19. '警情性質',
  20. '受害人姓名',
  21. '受害人賬號',
  22. '嫌疑人賬號',
  23. '嫌疑人電話',
  24. '涉案總金額',
  25. '案發時間',
  26. '警情狀態'
  27. ] // 匯出的excel的表頭欄位
  28. const filterVal = [
  29. 'alarmNo',
  30. 'alarmProp',
  31. 'informantName',
  32. 'informantBankAccount',
  33. 'suspectsAccount',
  34. 'suspectsMobile',
  35. 'fraudAmount',
  36. 'crimeTime',
  37. 'alarmStatus'
  38. ] // 物件屬性,對應於tHeader
  39. const list = this.$refs.inputTable.data
  40. const data = this.formatJson(filterVal, list)
  41. excel.export_json_to_excel({
  42. header: tHeader,
  43. data,
  44. filename: this.filename,
  45. autoWidth: this.autoWidth,
  46. bookType: this.bookType
  47. })
  48. this.downloadLoading = false
  49. })
  50. },
  51. // 格式轉換,直接複製即可
  52. formatJson(filterVal, jsonData) {
  53. return jsonData.map(v =>
  54. filterVal.map(j => {
  55. if (j === 'crimeTime') {
  56. return formatDate('YYYY-MM-DD HH:mm:ss', v[j] * 1000)
  57. } else if (j === 'alarmProp') {
  58. return this.alarmPropOptionsArr[v[j]]
  59. } else if (j === 'alarmStatus') {
  60. return this.alarmStatusOptionsArr[v[j]]
  61. } else {
  62. return v[j]
  63. }
  64. })
  65. )
  66. }

參見:https://panjiachen.gitee.io/vue-element-admin-site/zh/feature/component/excel.html

功能實現-資料統計與展示

單純的資料只有儲存的價值,而對儲存下來的資料進行相應的分析,並加以圖表的形式輸出,可以更直觀地看到資料的變化,體現資料的價值,實現新生代農民工的勞動價值。這邊結合echarts對某一個時間段的警情中各部分追查的佔比進行了一個統計,除此之外,對該時間段的每月的止付金額進行了一個統計,最終結合扇形和柱形對其進行展示。

翻一翻npm包,筆者物色到了兩位包包可以做這件事,考慮到針對本專案對於圖表的需求量不是特別大,我也懶得看兩套API,就還是用了echarts。

vue-echarts: https://www.npmjs.com/package/vue-echarts

echarts: https://www.npmjs.com/package/echarts

我們會有一個數據介面,前端帶上相關的請求引數通過請求/prod-api/statistics/calculate這個介面就能夠拿到後端的從資料庫處理出來的相關資料,這裡因為前後端都是我寫的,所以我制定的規則就是,所有的計算都有後端去完成,前端只負責展示,並且約定了相關的引數格式。這樣做的一個好處是,省去了前端這邊對資料的封裝處理。返回的格式如下:

  1. {
  2. "status": 200,
  3. "message": "success",
  4. "data": {
  5. "pieData": [
  6. {
  7. "name": "銀行查控",
  8. "count": 13
  9. },
  10. {
  11. "name": "電話查控",
  12. "count": 10
  13. },
  14. {
  15. "name": "虛擬賬號查控",
  16. "count": 3
  17. },
  18. {
  19. "name": "網站查控",
  20. "count": 5
  21. }
  22. ],
  23. "barData": [
  24. {
  25. "name": "2021年1月",
  26. "amount": 0
  27. },
  28. {
  29. "name": "2021年2月",
  30. "amount": 0
  31. },
  32. {
  33. "name": "2021年3月",
  34. "amount": 0
  35. },
  36. {
  37. "name": "2021年4月",
  38. "amount": 0
  39. },
  40. {
  41. "name": "2021年5月",
  42. "amount": 0
  43. },
  44. {
  45. "name": "2021年6月",
  46. "amount": 0
  47. },
  48. {
  49. "name": "2021年7月",
  50. "amount": 0
  51. },
  52. {
  53. "name": "2021年8月",
  54. "amount": 1311601
  55. }
  56. ],
  57. "totalAmount": 1311601
  58. }
  59. }

這裡以畫餅圖和柱形圖為例,其他的也是類似的,可以參考https://echarts.apache.org/examples/zh/index.html

公共部分

npm i echarts -S安裝echarts的npm包,然後在相應的檔案引入它。

  1. import echarts from 'echarts'
畫餅圖

在template中我們搞一個餅圖的div

  1. <div ref="pieChart" class="chart" />

在vue的方法裡面,我們定義一個畫餅的方法,這裡定義的輸入就是請求後端返回的資料,其他的看echarts的配置項,這邊都配好了(如果寫成單個元件,需要根據業務考慮相關的配置項,目前這邊就care資料項)。邏輯是這樣子的,定義了一個基於資料項變動的配置項options,然後當執行drawPie方法的時候,如果沒有初始化echarts,那麼我們這邊就初始化一個echarts的餅,如果有,那麼我們就只有更新相關的options就好了。

  1. drawPie(source) {
  2. const options = {
  3. title: {
  4. text: '各追查型別佔比統計'
  5. },
  6. tooltip: {
  7. trigger: 'item',
  8. formatter: '{b} : ({d}%)'
  9. },
  10. legend: {
  11. orient: 'vertical',
  12. x: 'left',
  13. y: 'bottom',
  14. data: ['銀行查控', '電話查控', '虛擬賬號查控', '網站查控']
  15. },
  16. dataset: {
  17. source
  18. },
  19. series: {
  20. type: 'pie',
  21. label: {
  22. position: 'outer',
  23. alignTo: 'edge',
  24. margin: 10,
  25. formatter: '{@name}: {@count} ({d}%)'
  26. },
  27. encode: {
  28. itemName: 'name',
  29. value: 'count'
  30. }
  31. }
  32. }
  33. if (this.pieChart) {
  34. this.pieChart.setOption(options, true)
  35. } else {
  36. this.pieChart = echarts.init(this.$refs.pieChart)
  37. this.pieChart.setOption(options, true)
  38. }
  39. }
畫柱形圖

跟樓上的類似的,畫柱子如樓下所示:

  1. drawBar(source) {
  2. const options = {
  3. title: {
  4. text: `各月份止付金額之和統計, 合計: ${this.totalAmount}元`
  5. },
  6. dataset: {
  7. source
  8. },
  9. xAxis: {
  10. type: 'category',
  11. name: '時間'
  12. },
  13. yAxis: [
  14. {
  15. type: 'value',
  16. name: '止付金額'
  17. }
  18. ],
  19. series: [
  20. {
  21. type: 'bar',
  22. encode: {
  23. x: 'name',
  24. y: 'amount'
  25. },
  26. label: {
  27. normal: {
  28. show: true,
  29. position: 'top'
  30. }
  31. }
  32. }
  33. ]
  34. }
  35. if (this.barChart) {
  36. this.barChart.setOption(options, true)
  37. } else {
  38. this.barChart = echarts.init(this.$refs.barChart)
  39. this.barChart.setOption(options, true)
  40. }
  41. },

備註:考慮到需求量不大,這裡筆者是為了趕進度偷懶寫成這樣的,學習的話,建議封裝成一個個元件,例如pie.vue,bar.vue這樣子去搞。

功能實現-頁面許可權控制和頁面許可權的按鈕許可權粒度控制

因為這個專案涉及到多個角色,這就涉及到對多個角色的頁面控制了,每個角色分配的頁面許可權是不一樣的,第二個就是進入到頁面後,針對某一條記錄,該登入使用者按鈕的許可權控制。

頁面許可權控制

頁面的許可權這邊有兩種做法,分別是控制權在前端,和控制權在後端兩種,在前端的話是通過獲取使用者資訊的角色,根據角色去匹配,匹配中了就加到路由裡面。在後端的話,就是登入的時候後端就把相應的路由返回給你,前端這邊註冊路由。

藉著vue-element-admin的東風,筆者這邊是將控制權放在前端,在路由的meta中加入roles角色去做頁面的許可權控制的。

參見 vue-element-admin - 路由和側邊欄:https://panjiachen.gitee.io/vue-element-admin-site/zh/guide/essentials/router-and-nav.html#配置項

參見 vue-element-admin - 許可權驗證: https://panjiachen.gitee.io/vue-element-admin-site/zh/guide/essentials/permission.html#邏輯修改

按鈕許可權控制

首先我們來分析下,針對我們這個系統,不外乎刪除、修改、詳情、稽核、追查等等按鈕許可權,不是特別多,所以我們可以用detailmodifydeleteauditcheck等去表示這些按鈕,後端在service層進行相關業務處理,把它們這些包到一個數組btnList裡面返回給前端,跟前端這邊做對比,如果命中那麼我們就展示按鈕。

核心程式碼如下:

template

  1. <template v-if="column.key === 'actions'">
  2. <el-table-column
  3. :key="column.key"
  4. align="center"
  5. :width="column.width"
  6. :label="column.title"
  7. >
  8. <template slot-scope="scope">
  9. <el-button
  10. v-for="action in filterOperate(
  11. column.actions,
  12. scope.row.btnList
  13. )"
  14. :key="action.type"
  15. type="text"
  16. size="small"
  17. @click="handleClick(scope.row, action.type, action.title)"
  18. >{{ action.title }}</el-button>
  19. </template>
  20. </el-table-column>
  21. </template>
  1. filterOperate(actions, btnList) {
  2. return actions.filter(action => btnList.includes(action.type))
  3. }

那麼我們就可以這麼使用了

  1. columns: [
  2. ......
  3. {
  4. title: '操作',
  5. key: 'actions',
  6. align: 'center',
  7. actions: [
  8. {
  9. title: '詳情',
  10. type: 'detail'
  11. },
  12. {
  13. title: '修改',
  14. type: 'modify'
  15. }
  16. ]
  17. }
  18. ]

關於許可權校驗這塊,筆者所在的供應鏈金融團隊是這麼去實現的,在保理業務中,會有很多個部門,比如市場部、財務部、風控部、董事會等等。每個部門裡又有經辦、稽核、複核等等角色。所以在處理這類業務中的許可權控制,需要將使用者身上繫結一個按鈕許可權,比如說他是市場的經辦角色,那麼他就可以繫結市場經辦這個角色的按鈕碼子上。前端這邊除了要在我們樓上的基礎上對列表返回的做對比之外,還有對使用者的做進一步對比。這裡的按鈕也不能夠像上面一樣detailmodify這樣去寫,因為角色多了每個角色這麼叫不好,更科學的應該是,整理成一份excel表,然後按照相應的按鈕許可權去配置相應的code(比如說 20001, 20002),然後根據這個去處理業務。

後端

eggjs中的三層模型(model-service-controller)

model層是對資料庫的相關表進行相應的對映和CRUD,service層是處理相關的業務邏輯,controller層是為相關的業務邏輯暴露介面。這三者層序漸進,一環扣一環。

Model
一些約定
  • 原則上,不允許對Model層SQL語句返回的結果進行相關操作,返回什麼就是什麼。
  • 統一下資料返回的格式
    • 語法錯誤 null
    • 查不到資料 false
    • 查到資料 JSON | Number
  • 統一下model層檔案類的通用方法
    • add: 新增
    • set: 更新
    • del: 刪除(本系統由於資料需要,所以不會真的刪除這條資料,而是取一哥isDelete欄位去軟刪除它)
    • get: 獲取單條資料,getById可簡寫成get, 若有查詢條件, 按getByCondition
    • getAll: 獲取多條記錄,若有查詢條件 按getAllByCondition
    • getAllLimit: 分頁獲取 若有查詢條件 按getAllLimitByCondition
    • has: 若有查詢條件, 按hasAttributes

目前本系統業務就用到這麼多,其他的參見sequelize文件: http://sequelize.org/

這樣做的好處是,一些概念和語義更加清晰了,比如有個user.js,裡面用add表示新增還是addUser表示新增好,我認為是前者,在user.js裡面, 除了新增user使用者,難不成還有別的新增,還能新增個鬼啊。除此之外,還方便了新生代農民工的複製貼上,提高編碼效率。

抄表字段真的好累啊

試想一下這樣一個場景,這個資料庫有一百張表,每張表有100個欄位,難道你真的要人肉去一個一個敲出來對應的資料庫對映嗎?那要敲到什麼時候啊,人都快搞沒了,我們可是新生代農民工唉,當然要跟上時代。 這裡介紹一下egg-sequelize-auto, 它可以快速的將資料庫的欄位對映到你的程式碼中,減少很多工作量。

安裝

  1. npm i egg-sequelize-auto -g
  2. npm i mysql2 -g

使用

  1. egg-sequelize-auto -h 'your ip' -d 'your database' -u 'db user' -x 'db password' -e mysql -o 'project model path' -t 'table name'

egg-sequelize-auto: https://www.npmjs.com/package/egg-sequelize-auto

sequelize連表查詢的應用

在表的關係中,有一對一,一對多,多對多。本系統一對多用的比較多,這裡就以銀行卡結合銀行的的連表做個演示。

主要是三個地方,一個是引入相關表的Model, 第二個是欄位初始化,第三個是通過associate方法建立聯絡,閹割後的示例程式碼如下:

  1. 'use strict';
  2. const OrganizationModel = require('./organization');
  3. module.exports = app => {
  4. const { logger, Sequelize, utils } = app;
  5. const { DataTypes, Model, Op } = Sequelize;
  6. class BankcardModel extends Model {
  7. static associate() {
  8. const { Organization } = app.model;
  9. BankcardModel.belongsTo(Organization, {
  10. foreignKey: 'bankId',
  11. targetKey: 'id',
  12. as: 'bank',
  13. });
  14. }
  15. static async getAllLimit(name, prefix, bankId, { page = 0, limit = 10 }) {
  16. let where = {};
  17. if (name) {
  18. where = { name: { [Op.like]: `%${name}%` } };
  19. }
  20. if (prefix) {
  21. where.prefix = { [Op.like]: `%${prefix}%` };
  22. }
  23. if (bankId) {
  24. where.bankId = bankId;
  25. }
  26. where.isDelete = 0;
  27. try {
  28. const offset = page < 1 ? 1 : (page - 1) * limit;
  29. const total = await this.count({ where });
  30. const last = Math.ceil(total / limit);
  31. const list =
  32. total === 0
  33. ? []
  34. : await this.findAll({
  35. raw: true,
  36. where,
  37. order: [
  38. ['createTime', 'DESC'],
  39. ['updateTime', 'DESC'],
  40. ],
  41. offset,
  42. limit,
  43. attributes: [
  44. 'id',
  45. 'name',
  46. 'prefix',
  47. 'bankId',
  48. [Sequelize.col('bank.name'), 'bankName'],
  49. ],
  50. include: {
  51. model: app.model.Organization,
  52. as: 'bank',
  53. attributes: [],
  54. },
  55. });
  56. logger.info(this.getAllLimit, page, limit, where, list);
  57. return {
  58. page,
  59. pageSize: limit,
  60. list,
  61. total,
  62. last,
  63. };
  64. } catch (e) {
  65. logger.error(e);
  66. return false;
  67. }
  68. }
  69. }
  70. BankcardModel.init(
  71. {
  72. id: {
  73. type: DataTypes.UUID,
  74. defaultValue() {
  75. return utils.generator.generateUUID();
  76. },
  77. allowNull: false,
  78. primaryKey: true,
  79. },
  80. name: {
  81. type: DataTypes.STRING(255),
  82. allowNull: true,
  83. },
  84. prefix: {
  85. type: DataTypes.STRING(255),
  86. allowNull: true,
  87. },
  88. bankId: {
  89. type: DataTypes.STRING(255),
  90. allowNull: false,
  91. references: {
  92. model: OrganizationModel,
  93. key: 'id',
  94. },
  95. },
  96. isDelete: {
  97. type: DataTypes.INTEGER(1),
  98. allowNull: true,
  99. defaultValue: 0,
  100. },
  101. createTime: {
  102. type: DataTypes.INTEGER(10),
  103. allowNull: true,
  104. },
  105. updateTime: {
  106. type: DataTypes.INTEGER(10),
  107. allowNull: true,
  108. },
  109. },
  110. {
  111. sequelize: app.model,
  112. tableName: 't_bankcard',
  113. }
  114. );
  115. return BankcardModel;
  116. };

sequelize中的表關係: https://sequelize.org/master/manual/assocs.html

Service

這裡就是引入相關的model層寫好的,然後根據業務邏輯去呼叫下,還是以銀行卡為例

  1. 'use strict';
  2. const { Service } = require('egg');
  3. class BankcardService extends Service {
  4. constructor(ctx) {
  5. super(ctx);
  6. this.Bankcard = this.ctx.model.Bankcard;
  7. }
  8. async add(name, prefix, bankId) {
  9. const { ctx, Bankcard } = this;
  10. let result = await Bankcard.hasPrefix(prefix);
  11. if (result) {
  12. ctx.throw('卡號字首已存在');
  13. }
  14. result = await Bankcard.add(name, prefix, bankId);
  15. if (!result) {
  16. ctx.throw('新增卡號失敗');
  17. }
  18. return result;
  19. }
  20. async getAllLimit(name, prefix, bankId, page, limit) {
  21. const { ctx, Bankcard } = this;
  22. const result = await Bankcard.getAllLimit(name, prefix, bankId, {
  23. page,
  24. limit,
  25. });
  26. if (!result) {
  27. ctx.throw('暫無資料');
  28. }
  29. return result;
  30. }
  31. async set(id, name, prefix, bankId, isDelete) {
  32. const { ctx, Bankcard } = this;
  33. const result = await Bankcard.set(id, name, prefix, bankId, isDelete);
  34. if (result === null) {
  35. ctx.throw('更新失敗');
  36. }
  37. return result;
  38. }
  39. }
  40. module.exports = BankcardService;
Controller
restful API介面

只要在相應的controller層定義相關的方法,egg程式就能夠根據restful api去解析。

Method Path Route Name Controller.Action
GET /posts posts app.controllers.posts.index
GET /posts/new new_post app.controllers.posts.new
GET /posts/:id post app.controllers.posts.show
GET /posts/:id/edit edit_post app.controllers.posts.edit
POST /posts posts app.controllers.posts.create
PUT /posts/:id post app.controllers.posts.update
DELETE /posts/:id post app.controllers.posts.destroy

參見:https://eggjs.org/zh-cn/basics/router.html

非restful API介面

這裡主要是針對於樓上的情況,進行一個補充,比如說使用者,除了這些,他還有登入,登出等等操作,那這個就需要單獨在router中制定了, 這裡筆者封裝了一個resource方法,來解析restful api的函式介面,具體如下:

  1. 'use strict';
  2. /**
  3. * @param {Egg.Application} app - egg application
  4. */
  5. module.exports = app => {
  6. const { router, controller } = app;
  7. router.get('/', controller.home.index);
  8. router.post('/user/login', controller.user.login);
  9. router.post('/user/logout', controller.user.logout);
  10. router.post('/user/info', controller.user.getUserInfo);
  11. router.post('/file/upload', controller.file.upload);
  12. router.post('/file/getall', controller.file.getAllByIds);
  13. router.post('/organization/by-type', controller.organization.getAllByType);
  14. router.post('/statistics/calculate', controller.statistics.calculate);
  15. function resource(path) {
  16. const pathArr = path.split('/');
  17. // 刪掉第一個空白的
  18. pathArr.shift();
  19. let controllers = controller;
  20. for (const val of pathArr) {
  21. controllers = controllers[val];
  22. }
  23. router.resources(path, path, controllers);
  24. }
  25. resource('/alarm');
  26. resource('/bank');
  27. resource('/bankcard');
  28. resource('/mobile');
  29. resource('/organization');
  30. resource('/user');
  31. resource('/virtual');
  32. resource('/website');
  33. resource('/file');
  34. resource('/alarmCategory');
  35. };

這裡還是以銀行卡為例

  1. 'use strict';
  2. const { Controller } = require('egg');
  3. class BankCardController extends Controller {
  4. async index() {
  5. const { ctx, service } = this;
  6. const { name, prefix, bankId, page, pageSize } = ctx.request.query;
  7. const { list, ...rest } = await service.bankcard.getAllLimit(
  8. name,
  9. prefix,
  10. bankId,
  11. Number(page),
  12. Number(pageSize)
  13. );
  14. const data = list.map(item => {
  15. const { role } = ctx.session.userinfo;
  16. let btnList = [];
  17. if (role === 'admin') {
  18. btnList = ['detail', 'modify', 'delete'];
  19. }
  20. return {
  21. btnList,
  22. ...item,
  23. };
  24. });
  25. ctx.success({ list: data, ...rest });
  26. }
  27. async create() {
  28. const { ctx, service } = this;
  29. const { name, prefix, bankId } = ctx.request.body;
  30. ctx.validate(
  31. {
  32. name: { type: 'string', required: true },
  33. prefix: { type: 'string', required: true },
  34. bankId: { type: 'string', required: true },
  35. },
  36. { name, prefix, bankId }
  37. );
  38. const result = await service.bankcard.add(name, prefix, bankId);
  39. ctx.success(result);
  40. }
  41. // async destory() {
  42. // const { ctx, service } = this;
  43. // const { method } = ctx;
  44. // this.ctx.body = '刪除';
  45. // }
  46. async update() {
  47. const { ctx, service } = this;
  48. const { id } = ctx.params;
  49. const { name, prefix, bankId, isDelete } = ctx.request.body;
  50. const result = await service.bankcard.set(
  51. id,
  52. name,
  53. prefix,
  54. bankId,
  55. isDelete
  56. );
  57. ctx.success(result);
  58. }
  59. async show() {
  60. const { ctx, service } = this;
  61. const { method } = ctx;
  62. this.ctx.body = '查詢';
  63. }
  64. async new() {
  65. const { ctx, service } = this;
  66. const { method } = ctx;
  67. this.ctx.body = '建立頁面';
  68. }
  69. async edit() {
  70. const { ctx, service } = this;
  71. const { method } = ctx;
  72. this.ctx.body = '修改頁面';
  73. }
  74. }
  75. module.exports = BankCardController;

至此,打通這樣一個從model到service再到controller的流程,

eggjs中的定時任務schedule

原系統是接入了第三方的資料來源去定時讀取更新資料,再將資料清洗更新到我們自己的t_alarm表,一些原因這裡我不方便做演示,所以筆者又新建了一張天氣表,來向大家介紹eggjs中的定時任務。

在這裡,我相中了萬年曆的介面,準備嫖一嫖給大家做一個演示的例子,它返回的資料格式如下

  1. {
  2. "data": {
  3. "yesterday": {
  4. "date": "19日星期四",
  5. "high": "高溫 33℃",
  6. "fx": "東風",
  7. "low": "低溫 24℃",
  8. "fl": "<![CDATA[1級]]>",
  9. "type": "小雨"
  10. },
  11. "city": "杭州",
  12. "forecast": [
  13. {
  14. "date": "20日星期五",
  15. "high": "高溫 34℃",
  16. "fengli": "<![CDATA[2級]]>",
  17. "low": "低溫 25℃",
  18. "fengxiang": "西南風",
  19. "type": "小雨"
  20. },
  21. {
  22. "date": "21日星期六",
  23. "high": "高溫 33℃",
  24. "fengli": "<![CDATA[2級]]>",
  25. "low": "低溫 25℃",
  26. "fengxiang": "西南風",
  27. "type": "中雨"
  28. },
  29. {
  30. "date": "22日星期天",
  31. "high": "高溫 33℃",
  32. "fengli": "<![CDATA[1級]]>",
  33. "low": "低溫 26℃",
  34. "fengxiang": "東風",
  35. "type": "小雨"
  36. },
  37. {
  38. "date": "23日星期一",
  39. "high": "高溫 32℃",
  40. "fengli": "<![CDATA[1級]]>",
  41. "low": "低溫 26℃",
  42. "fengxiang": "南風",
  43. "type": "中雨"
  44. },
  45. {
  46. "date": "24日星期二",
  47. "high": "高溫 33℃",
  48. "fengli": "<![CDATA[1級]]>",
  49. "low": "低溫 25℃",
  50. "fengxiang": "西南風",
  51. "type": "小雨"
  52. }
  53. ],
  54. "ganmao": "感冒低發期,天氣舒適,請注意多吃蔬菜水果,多喝水哦。",
  55. "wendu": "31"
  56. },
  57. "status": 1000,
  58. "desc": "OK"
  59. }

我分別選取了天朝的一線城市和一些地域性比較強的城市去搞資料(等跑個兩三個月,存了點資料,俺又可以寫一篇基於echarts的天氣視覺化展示了,233333333),最後的效果如圖

首先我們建立一個類,繼承了egg的Subscription類, 然後有一個schedule方法

  1. static get schedule() {
  2. return {
  3. interval: '12h',
  4. type: 'worker',
  5. };
  6. }

interval表示時間間隔,從樓上可以看出是每12小時去執行一次,type表示執行這個定時任務的程序,可以選allworker,這邊表示只在一個worker程序中執行該任務。

核心的業務邏輯,寫在subscribe方法中,這裡表示去請求萬年曆的資料,然後進行相應的資料清洗

  1. async subscribe() {
  2. try {
  3. const result = [];
  4. for (const city of CITYS) {
  5. result.push(this.fetchData(city));
  6. }
  7. await Promise.all(result);
  8. } catch (e) {
  9. this.ctx.app.logger.error(e);
  10. }
  11. }

最終實現程式碼如下:

  1. const { Subscription } = require('egg');
  2. const URL_PREFIX = 'http://wthrcdn.etouch.cn/weather_mini?city=';
  3. const CITYS = [
  4. '杭州',
  5. '北京',
  6. '南京',
  7. '上海',
  8. '廣州',
  9. '深圳',
  10. '成都',
  11. '武漢',
  12. '鄭州',
  13. '哈爾濱',
  14. '海口',
  15. '三亞',
  16. '烏魯木齊',
  17. '呼和浩特',
  18. '拉薩',
  19. '大理',
  20. '麗江',
  21. ];
  22. const DAY_TIMESTAMP = 86400000;
  23. class WeatherSchedule extends Subscription {
  24. static get schedule() {
  25. return {
  26. interval: '12h',
  27. type: 'worker',
  28. };
  29. }
  30. async refreshWeatherData(
  31. date,
  32. high,
  33. low,
  34. wendu = null,
  35. fengli,
  36. fengxiang,
  37. type,
  38. ganmao = null,
  39. city,
  40. weatherDate
  41. ) {
  42. const weather = await this.service.weather.getWeather(weatherDate, city);
  43. if (weather) {
  44. const { id, wendu: oldWendu, ganmao: oldGanmao } = weather;
  45. const newWendu = oldWendu || wendu;
  46. const newGanmao = oldGanmao || ganmao;
  47. await this.service.weather.set(
  48. id,
  49. date,
  50. high,
  51. low,
  52. newWendu,
  53. fengli,
  54. fengxiang,
  55. type,
  56. newGanmao,
  57. city,
  58. weatherDate
  59. );
  60. } else {
  61. await this.service.weather.add(
  62. date,
  63. high,
  64. low,
  65. wendu,
  66. fengli,
  67. fengxiang,
  68. type,
  69. ganmao,
  70. city,
  71. weatherDate
  72. );
  73. }
  74. }
  75. async fetchData(queryCity) {
  76. const res = await this.ctx.curl(`${URL_PREFIX}${queryCity}`, {
  77. dataType: 'json',
  78. });
  79. const {
  80. data: { city, forecast = [], ganmao, wendu },
  81. } = res.data;
  82. const result = [];
  83. const now = this.ctx.app.utils.date.now() * 1000;
  84. for (let i = 0; i < forecast.length; i++) {
  85. const { date, high, fengli, low, fengxiang, type } = forecast[i];
  86. const weatherDate = this.ctx.app.utils.date.format2Date(
  87. now + i * DAY_TIMESTAMP
  88. );
  89. if (i === 0) {
  90. result.push(
  91. this.refreshWeatherData(
  92. date,
  93. high,
  94. low,
  95. wendu,
  96. fengli,
  97. fengxiang,
  98. type,
  99. ganmao,
  100. city,
  101. weatherDate
  102. )
  103. );
  104. } else {
  105. result.push(
  106. this.refreshWeatherData(
  107. date,
  108. high,
  109. low,
  110. null,
  111. fengli,
  112. fengxiang,
  113. type,
  114. null,
  115. city,
  116. weatherDate
  117. )
  118. );
  119. }
  120. }
  121. await Promise.all(result);
  122. }
  123. async subscribe() {
  124. try {
  125. const result = [];
  126. for (const city of CITYS) {
  127. result.push(this.fetchData(city));
  128. }
  129. await Promise.all(result);
  130. } catch (e) {
  131. this.ctx.app.logger.error(e);
  132. }
  133. }
  134. }
  135. module.exports = WeatherSchedule;

egg中的schedule: https://eggjs.org/zh-cn/basics/schedule.html

eggjs中的配置項config

eggjs提供了根據開發、生產、測試環境的配置檔案,具體的以config.env.js表示,因為專案不是很複雜,而且都是我一個人寫的,這裡就簡單點都寫在了一個檔案config.default.js裡面。

在這裡面可以對中介軟體、安全、資料庫、日誌、檔案上傳、session、loader等進行配置,具體的如下:

  1. /* eslint valid-jsdoc: "off" */
  2. 'use strict';
  3. /**
  4. * @param {Egg.EggAppInfo} appInfo app info
  5. */
  6. module.exports = appInfo => {
  7. /**
  8. * built-in config
  9. * @type {Egg.EggAppConfig}
  10. * */
  11. const config = (exports = {});
  12. // use for cookie sign key, should change to your own and keep security
  13. config.keys = `${appInfo.name}_ataola`;
  14. // add your middleware config here
  15. config.middleware = ['cost', 'errorHandler'];
  16. // add your user config here
  17. const userConfig = {
  18. myAppName: 'egg',
  19. };
  20. config.security = {
  21. xframe: {
  22. enable: true,
  23. },
  24. csrf: {
  25. enable: true,
  26. ignore: '/user/login',
  27. // queryName: '_csrf',
  28. // bodyName: '_csrf',
  29. headerName: 'x-csrf-token',
  30. },
  31. domainWhiteList: [
  32. 'http://localhost:7001',
  33. 'http://127.0.0.1:7001',
  34. 'http://localhost:9528',
  35. 'http://localhost',
  36. 'http://127.0.0.1',
  37. ],
  38. };
  39. // https://github.com/eggjs/egg-sequelize
  40. config.sequelize = {
  41. dialect: 'mysql', // support: mysql, mariadb, postgres, mssql
  42. database: 'anti-fraud',
  43. host: 'hzga-mysql',
  44. port: 3306,
  45. username: 'root',
  46. password: 'ataola',
  47. // delegate: 'myModel', // load all models to `app[delegate]` and `ctx[delegate]`, default to `model`
  48. // baseDir: 'my_model', // load all files in `app/${baseDir}` as models, default to `model`
  49. // exclude: 'index.js', // ignore `app/${baseDir}/index.js` when load models, support glob and array
  50. // more sequelize options
  51. define: {
  52. timestamps: false,
  53. underscored: false,
  54. },
  55. };
  56. exports.multipart = {
  57. mode: 'file',
  58. fileSize: '100mb',
  59. whitelist: [
  60. // images
  61. '.jpg',
  62. '.jpeg', // image/jpeg
  63. '.png', // image/png, image/x-png
  64. '.gif', // image/gif
  65. '.bmp', // image/bmp
  66. '.wbmp', // image/vnd.wap.wbmp
  67. '.webp',
  68. '.tif',
  69. '.psd',
  70. // text
  71. '.svg',
  72. '.js',
  73. '.jsx',
  74. '.json',
  75. '.css',
  76. '.less',
  77. '.html',
  78. '.htm',
  79. '.xml',
  80. '.xlsx',
  81. '.xls',
  82. '.doc',
  83. '.docx',
  84. '.ppt',
  85. '.pptx',
  86. '.pdf',
  87. // tar
  88. '.zip',
  89. '.rar',
  90. '.gz',
  91. '.tgz',
  92. '.gzip',
  93. // video
  94. '.mp3',
  95. '.mp4',
  96. '.avi',
  97. ],
  98. };
  99. config.session = {
  100. key: 'SESSION_ID', // 設定session key,cookie裡面的key
  101. maxAge: 24 * 3600 * 1000, // 1 天
  102. httpOnly: true, // 是否允許js訪問session,預設為true,表示不允許js訪問
  103. encrypt: true, // 是否加密
  104. renew: true, // 重置session的過期時間,延長session過期時間
  105. };
  106. config.logger = {
  107. level: 'NONE',
  108. consoleLevel: 'DEBUG',
  109. disableConsoleAfterReady: false,
  110. };
  111. config.errorHandler = {
  112. match: '/',
  113. };
  114. config.customLoader = {
  115. enum: {
  116. directory: 'app/enum',
  117. inject: 'app',
  118. loadunit: true,
  119. },
  120. utils: {
  121. directory: 'app/utils',
  122. inject: 'app',
  123. loadunit: true,
  124. },
  125. };
  126. config.cluster = {
  127. listen: {
  128. path: '',
  129. port: 7001,
  130. hostname: '0.0.0.0',
  131. },
  132. };
  133. return {
  134. ...config,
  135. ...userConfig,
  136. };
  137. };

eggjs中的配置:https://eggjs.org/zh-cn/basics/config.html

eggjs中的外掛

這裡主要是針對一些egg整合的外掛進行配置,比如sequelize, cors等等

plugin.js具體的如下:

  1. 'use strict';
  2. /** @type Egg.EggPlugin */
  3. module.exports = {
  4. // had enabled by egg
  5. static: {
  6. enable: true,
  7. },
  8. sequelize: {
  9. enable: true,
  10. package: 'egg-sequelize',
  11. },
  12. cors: {
  13. enable: true,
  14. package: 'egg-cors',
  15. },
  16. validate: {
  17. enable: true,
  18. package: 'egg-validate',
  19. },
  20. };

eggjs中的外掛: https://eggjs.org/zh-cn/basics/plugin.html

eggjs中的擴充套件extend

在app資料夾下新建extend資料夾,它可以對egg的agent,application,context,helper,request,response,validator內建物件進行擴充套件。

這裡以context.js為例,我想封裝一下上下文返回的格式,可以這麼寫:

  1. 'use strict';
  2. module.exports = {
  3. success(data, message = 'success') {
  4. const res = {
  5. status: 200,
  6. message,
  7. data,
  8. };
  9. this.app.logger.info(JSON.stringify(res));
  10. this.body = res;
  11. },
  12. };

呼叫的時候ctx.success(data)

eggjs中的擴充套件:https://eggjs.org/zh-cn/basics/extend.html

eggjs中的中介軟體

比如說我想編寫一個請求響應時間的中介軟體,那麼可以在app資料夾下新建middleware資料夾,然後新建cost.js檔案

  1. // app/middleware/cost.js
  2. module.exports = options => {
  3. const header = options.header || 'X-Response-Time';
  4. return async function cost(ctx, next) {
  5. const now = Date.now();
  6. await next();
  7. ctx.set(header, `${Date.now() - now}ms`);
  8. };
  9. };

config/config.default.js檔案中,我們註冊它

  1. // add your middleware config here
  2. config.middleware = ['cost', 'errorHandler'];

這樣在請求響應的時候就會帶上一個x-Response-Time

eggjs中的中介軟體:https://eggjs.org/zh-cn/basics/middleware.html

eggjs中的通用工具包

比如你想寫一些通用的工具類, 那麼可以這麼去做,在app目錄下新建utils資料夾,然後建立一個generator.js(這裡以生成id舉例), 程式碼如下:

  1. const { v4: uuidv4 } = require('uuid');
  2. function generateUUID() {
  3. return uuidv4().replace(/-/g, '');
  4. }
  5. function getNo(num) {
  6. const numStr = `000${(num % 1000).toString()}`;
  7. return numStr.slice(-3);
  8. }
  9. module.exports = {
  10. generateUUID,
  11. getNo,
  12. };

然後再config/config.default.js中配置

  1. config.customLoader = {
  2. utils: {
  3. directory: 'app/utils',
  4. inject: 'app',
  5. loadunit: true,
  6. },
  7. };

它表示載入app/utils下面的檔案,注入到application物件中。呼叫的時候就可以直接app.utils.generateUUID()

功能實現-檔案上傳與下載

egg內建了multipart外掛,通過這個外掛我們很容易實現檔案上傳

  1. async upload() {
  2. const { ctx, service } = this;
  3. const file = ctx.request.files[0];
  4. if (!file) return ctx.throw(404);
  5. // const filename = path.extname(file.filename).toLowerCase();
  6. const { filename } = file;
  7. const type = path.extname(filename).toLowerCase();
  8. const { username, nickname } = ctx.session.userinfo;
  9. const createBy = nickname || username;
  10. const uuid = ctx.app.utils.generator.generateUUID();
  11. const targetPathPrefix = path.join(this.config.baseDir, 'app/public', uuid);
  12. const targetPath = path.join(
  13. this.config.baseDir,
  14. 'app/public',
  15. uuid,
  16. filename
  17. );
  18. const source = fs.createReadStream(file.filepath);
  19. await mkdirp(targetPathPrefix);
  20. const target = fs.createWriteStream(targetPath);
  21. let result = '';
  22. try {
  23. await pump(source, target);
  24. const stats = fs.statSync(targetPath);
  25. const size = ctx.app.utils.compute.bytesToSize(stats.size);
  26. const url = `public/${uuid}/${filename}`;
  27. result = await service.file.add(filename, type, size, url, createBy);
  28. ctx.logger.info('save %s to %s', file.filepath, targetPath, stats, size);
  29. } finally {
  30. // delete those request tmp files
  31. await ctx.cleanupRequestFiles();
  32. }
  33. ctx.success(result);
  34. }

上面的程式碼就是在讀取前端傳過來的檔案後,在app/public資料夾下建立檔案,並將記錄寫到資料庫中

config/config.default.js中可以對檔案進行相關配置,比如說模式是流還是檔案,相關檔案的大小,相關檔案的格式等。

  1. exports.multipart = {
  2. mode: 'file',
  3. fileSize: '100mb',
  4. whitelist: [
  5. // images
  6. '.jpg',
  7. '.jpeg', // image/jpeg
  8. '.png', // image/png, image/x-png
  9. '.gif', // image/gif
  10. '.bmp', // image/bmp
  11. '.wbmp', // image/vnd.wap.wbmp
  12. '.webp',
  13. '.tif',
  14. '.psd',
  15. // text
  16. '.svg',
  17. '.js',
  18. '.jsx',
  19. '.json',
  20. '.css',
  21. '.less',
  22. '.html',
  23. '.htm',
  24. '.xml',
  25. '.xlsx',
  26. '.xls',
  27. '.doc',
  28. '.docx',
  29. '.ppt',
  30. '.pptx',
  31. '.pdf',
  32. // tar
  33. '.zip',
  34. '.rar',
  35. '.gz',
  36. '.tgz',
  37. '.gzip',
  38. // video
  39. '.mp3',
  40. '.mp4',
  41. '.avi',
  42. ],
  43. };

eggjs中的檔案上傳: https://eggjs.github.io/zh/guide/upload.html

egg-multipart: https://github.com/eggjs/egg-multipart

功能實現-資料統計

在Model層,需要對進行一定範圍的查詢,如下:

  1. static async getTotal(start, end) {
  2. const where = {
  3. crimeTime: {
  4. [Op.between]: [start, end],
  5. },
  6. };
  7. try {
  8. const ret = await this.count({ where });
  9. logger.info(this.getTotal, start, end, ret);
  10. return ret;
  11. } catch (e) {
  12. logger.error(e);
  13. return false;
  14. }
  15. }

可能細心的讀者發現了,我這邊儲存資料用的是時間戳,一個月的時間戳是2592000。所以這邊想要取一個月的資料就很簡單了框定範圍[start, start + 2592000]就好了。

以餅圖的為例, service層程式碼如下:

  1. async calculateCount(start, end) {
  2. const { Bank, Mobile, Virtual, Website } = this;
  3. const bankCount = await Bank.getTotal(start, end + 2592000);
  4. const mobileCount = await Mobile.getTotal(start, end + 2592000);
  5. const virtualCount = await Virtual.getTotal(start, end + 2592000);
  6. const websiteCount = await Website.getTotal(start, end + 2592000);
  7. return [
  8. { name: '銀行查控', count: bankCount || 0 },
  9. { name: '電話查控', count: mobileCount || 0 },
  10. { name: '虛擬賬號查控', count: virtualCount || 0 },
  11. { name: '網站查控', count: websiteCount || 0 },
  12. ];
  13. }

controller層的程式碼如下(這邊其實可以用Promise.all進行優化,參考schedule那個例子,讀者試著改一下吧,因為它觸發了eslint的這個規則,/* eslint-disable no-await-in-loop */, 不建議在迴圈中用await):

  1. async calculate() {
  2. const { ctx, service } = this;
  3. const { start, end } = ctx.request.body;
  4. const startUinx = this.ctx.app.utils.date.transformDate(start);
  5. const endUnix = this.ctx.app.utils.date.transformDate(end);
  6. const pieData = await service.statistics.calculateCount(startUinx, endUnix);
  7. const monthArr = this.ctx.app.utils.date.getMonthArr(start, end);
  8. const barData = [];
  9. let totalAmount = 0;
  10. for (const month of monthArr) {
  11. const { name, value } = month;
  12. const unix = this.ctx.app.utils.date.transformDate(value);
  13. const amount = await service.statistics.calculateAmount(unix);
  14. totalAmount += amount;
  15. barData.push({ name, amount });
  16. }
  17. ctx.success({ pieData, barData, totalAmount });
  18. }

功能實現-按鈕許可權控制

這裡以銀行查控為例,主要是根據相關的使用者角色和記錄的狀態去判斷它有什麼按鈕許可權,具體的程式碼如下:

  1. async index() {
  2. const { ctx, service } = this;
  3. const { alarmNo, account, bankId, accountType, page, pageSize } =
  4. ctx.request.query;
  5. const { list, ...rest } = await service.bank.getAllLimit(
  6. alarmNo,
  7. account,
  8. bankId,
  9. accountType,
  10. Number(page),
  11. Number(pageSize)
  12. );
  13. const data = list.map(item => {
  14. const { role } = ctx.session.userinfo;
  15. const { status } = item;
  16. let btnList = [];
  17. if (role === 'operator') {
  18. if (status === 0) {
  19. btnList = ['check', 'detail'];
  20. } else if (status === 1) {
  21. btnList = ['detail'];
  22. }
  23. } else {
  24. btnList = ['detail'];
  25. }
  26. return {
  27. btnList,
  28. ...item,
  29. };
  30. });
  31. ctx.success({ list: data, ...rest });
  32. }

部署實施

傳統方式一個一個來(以ubuntu21.04舉例)

能聯網

第一步:

mysql的安裝: apt-get install mysql-server

nginx的安裝: apt-get install nginx

nodejs的安裝 : apt-get install nodejs

第二步:

配置nignx、mysql開機自啟動(略),nodejs這邊的程式建議用pm2管理,具體的步驟如下

安裝pm2

  1. npm i pm2 -g

egg程式設定pm2管理,根目錄新增server.js

  1. // server.js
  2. const egg = require('egg');
  3. // eslint-disable-next-line global-require
  4. const workers = Number(process.argv[2] || require('os').cpus().length);
  5. egg.startCluster({
  6. workers,
  7. baseDir: __dirname,
  8. port: 7001,
  9. });

對pm2程式進行配置,根目錄新增ecosystem.config.js

  1. module.exports = {
  2. apps: [
  3. {
  4. name: 'server',
  5. script: './server.js',
  6. instances: '1',
  7. exec_mode: 'cluster',
  8. env: {
  9. COMMON_VARIABLE: 'true',
  10. NODE_ENV: 'production',
  11. PORT: 7001,
  12. },
  13. },
  14. ],
  15. };

package.json的scripts中中新增指令碼

  1. "pm2": "pm2 start server.js --env ecosystem.config.js"

設定pm2開機自啟動

  1. pm2 startup
  2. pm2 save

pm2文件: https://pm2.keymetrics.io/docs/usage/quick-start/

eggjs程式用pm2管理: https://eggjs.org/zh-cn/faq.html#程序管理為什麼沒有選型-pm2

這裡寫的eggjs程式官網是不推薦用pm2管理的,在開發環境有egg-bin,生產環境有egg-script,我這邊主要是考慮到,伺服器那邊環境沒有我們阿里雲或者騰訊雲上面操作方便,需要考慮宕機後系統的重啟,而PM2剛好具備這些特性(管理node程式,開機自啟動管理的node程式),俺也懶得寫啟動指令碼,就在選型上用pm2去管理,後面上了docker以後,那就沒這麼多雜事了。

不能聯網

阿西吧,這個就比較頭大了。這邊就提供兩個思路,第一個是組網,就是用你的電腦拉一根網線跟伺服器組一個區域網,然後共享你的網路,這裡需要注意的是,伺服器可能 會有多個網絡卡,你需要確保你所配置的那張網絡卡是對的,這邊有兩個辦法,第一個是眼睛睜大看網口上有沒有標號, 第二個就是暴力組網,在你的宿主機上,使用ping 伺服器內網配置ip -t 去測,直到發現那個正確的網絡卡。組完網,參照樓上的就跑一遍唄。

第二個就異常痛苦啦,實在連不上網,就需要提前下載相關的原始碼包(這裡比較頭大的是,一些不確定的依賴,比如編譯安裝的時候,可能需要下c++的庫),掛載到伺服器上一個一個解壓編譯安裝,emmmmmmmm,太痛苦了,放棄治療吧,我選docker。

優劣勢

沒看出有啥優勢,頭皮發麻,2333333333。

docker一把梭

Dockerfile的編寫

通過docker build命令執行Dockerfile,我們可以得到相應的映象,然後通過docker run 相應的映象我們可以得到相應的容器,注意這裡run命令要慎用,因為每執行一次都會建立一層映象,你可以把多條命令用&&放到一起,或者放到CMD命令中,CMD是容器跑起來的時候執行的命令。

前端(以hzga-fe為例)

這裡表示是基於node14.8.0的映象,建立人是ataola,以/app為工作目錄,拷貝相關的檔案到工作目錄,然後執行相關的命令構建映象,在構建完以後,基於nginx1.17.2的映象,將打包好後的檔案拷貝到nginx中,暴露80埠,在容器跑起來的時候執行CMD的命令。

  1. # build stage
  2. FROM node:14.8.0 as build-stage
  3. MAINTAINER ataola <zjt613@gmail.com>
  4. WORKDIR /app
  5. COPY package.json ./
  6. COPY nginx ./nginx/
  7. COPY public ./public/
  8. COPY .editorconfig .env.* .eslintrc.js .eslintignore .prettierrc jsconfig.json *.config.js ./
  9. COPY src ./src/
  10. COPY build ./build/
  11. RUN npm install --registry=https://registry.npm.taobao.org cnpm -g \
  12. && SASS_BINARY_SITE=https://npm.taobao.org/mirrors/node-sass/ cnpm install --registry=https://registry.npm.taobao.org \
  13. && npm rebuild node-sass \
  14. && npm run build:prod
  15. # production stage
  16. FROM nginx:1.17.2-alpine-perl as production-stage
  17. COPY --from=build-stage /app/dist /usr/share/nginx/html
  18. COPY --from=build-stage /app/nginx /etc/nginx/
  19. VOLUME /app
  20. EXPOSE 80
  21. CMD ["nginx", "-g", "daemon off;"]

nginx.conf配置檔案如下


  1. #user nobody;
  2. worker_processes 1;
  3. #error_log logs/error.log;
  4. #error_log logs/error.log notice;
  5. #error_log logs/error.log info;
  6. #pid logs/nginx.pid;
  7. events {
  8. worker_connections 1024;
  9. }
  10. http {
  11. include mime.types;
  12. default_type application/octet-stream;
  13. #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  14. # '$status $body_bytes_sent "$http_referer" '
  15. # '"$http_user_agent" "$http_x_forwarded_for"';
  16. #access_log logs/access.log main;
  17. sendfile on;
  18. #tcp_nopush on;
  19. #keepalive_timeout 0;
  20. keepalive_timeout 65;
  21. #gzip on;
  22. upstream eggServer {
  23. server hzga-be:7001;
  24. }
  25. server {
  26. listen 80;
  27. server_name hzga-fe;
  28. #charset koi8-r;
  29. #access_log logs/host.access.log main;
  30. location / {
  31. root /usr/share/nginx/html;
  32. index index.html index.htm;
  33. try_files $uri $uri/ =404;
  34. }
  35. location /prod-api {
  36. rewrite /prod-api/(.*) /$1 break;
  37. client_max_body_size 100M;
  38. proxy_pass http://eggServer;
  39. proxy_http_version 1.1;
  40. proxy_set_header Upgrade $http_upgrade;
  41. proxy_set_header Connection 'upgrade';
  42. proxy_set_header Host $host;
  43. proxy_cache_bypass $http_upgrade;
  44. }
  45. #error_page 404 /404.html;
  46. # redirect server error pages to the static page /50x.html
  47. #
  48. error_page 500 502 503 504 /50x.html;
  49. location = /50x.html {
  50. root html;
  51. }
  52. # proxy the PHP scripts to Apache listening on 127.0.0.1:80
  53. #
  54. #location ~ \.php$ {
  55. # proxy_pass http://127.0.0.1;
  56. #}
  57. # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
  58. #
  59. #location ~ \.php$ {
  60. # root html;
  61. # fastcgi_pass 127.0.0.1:9000;
  62. # fastcgi_index index.php;
  63. # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
  64. # include fastcgi_params;
  65. #}
  66. # deny access to .htaccess files, if Apache's document root
  67. # concurs with nginx's one
  68. #
  69. #location ~ /\.ht {
  70. # deny all;
  71. #}
  72. }
  73. # another virtual host using mix of IP-, name-, and port-based configuration
  74. #
  75. #server {
  76. # listen 8000;
  77. # listen somename:8080;
  78. # server_name somename alias another.alias;
  79. # location / {
  80. # root html;
  81. # index index.html index.htm;
  82. # }
  83. #}
  84. # HTTPS server
  85. #
  86. #server {
  87. # listen 443 ssl;
  88. # server_name localhost;
  89. # ssl_certificate cert.pem;
  90. # ssl_certificate_key cert.key;
  91. # ssl_session_cache shared:SSL:1m;
  92. # ssl_session_timeout 5m;
  93. # ssl_ciphers HIGH:!aNULL:!MD5;
  94. # ssl_prefer_server_ciphers on;
  95. # location / {
  96. # root html;
  97. # index index.html index.htm;
  98. # }
  99. #}
  100. }
後端 (以hzga-be為例)

參考樓上hzga-fe的釋義。

  1. FROM node:14.8.0
  2. MAINTAINER ataola <zjt613@gmail.com>
  3. WORKDIR /app
  4. COPY package.json ./
  5. RUN npm install --registry=https://registry.npm.taobao.org --production
  6. COPY app ./app
  7. COPY config ./config
  8. COPY .eslintrc .eslintignore .prettierrc .autod.conf.js .editorconfig app.js jsconfig.json ./
  9. VOLUME /app
  10. EXPOSE 7001
  11. CMD ["npm", "run", "docker"]
MySQL資料庫(以hzga-mysql為例)

參考樓上的樓上hzga-fe的釋義, 與之不同的是,這裡通過配置設定了建庫指令碼,使用者名稱密碼。

  1. FROM mysql:8.0.16
  2. MAINTAINER ataola<zjt613@gmail.com>
  3. ENV MYSQL_DATABASE anti-fraud
  4. ENV MYSQL_ROOT_PASSWORD ataola
  5. ENV MYSQL_ROOT_HOST '%'
  6. ENV AUTO_RUN_DIR ./docker-entrypoint-initdb.d
  7. ENV INIT_SQL anti-fraud.sql
  8. COPY ./$INIT_SQL $AUTO_RUN_DIR/
  9. RUN chmod a+x $AUTO_RUN_DIR/$INIT_SQL
  10. VOLUME /app
  11. EXPOSE 3306

docker-compose.yml的編寫

我們開發會涉及到前端、後端、資料庫。docker-compose可以把多個容器放在一起管理,預設會建立一個網路,通過相關的服務名就可以訪問,比如說,hzga-be的後端服務想要訪問hzga-mysql的資料庫,那麼就可以直接在配置檔案中,將ip改成hzga-mysql。同理,前端nginx這邊的代理,如果要訪問後端,那麼可以在代理的位置直接寫haga-be。

docker-compose.yml檔案如下:

這裡表示是基於docker-compose 3.3版本的, 然後有三個service,分別是hzga-fe(前端),hzga-be(後端),hzga-mysql(MYSQL資料庫),然後指定了Dockerfile的位置,製作成映象後的名字,暴露了相應的埠,然後容器的名字,失敗後的重啟策略,以及建立的網路的名字,其中後端的服務hzga-be基於資料庫hzga-mysql

  1. version: '3.3'
  2. services:
  3. hzga-fe:
  4. build:
  5. context: ./anti-fraud-system-fe
  6. dockerfile: Dockerfile
  7. image: ataola/hzga-fe:0.0.1
  8. ports:
  9. - "80:80"
  10. networks:
  11. - net-hzga
  12. container_name: hzga-fe
  13. restart: on-failure
  14. hzga-be:
  15. build:
  16. context: ./anti-fraud-system-be
  17. dockerfile: Dockerfile
  18. image: ataola/hzga-be:0.0.1
  19. ports:
  20. - "7001:7001"
  21. depends_on:
  22. - hzga-mysql
  23. networks:
  24. - net-hzga
  25. container_name: hzga-be
  26. restart: on-failure
  27. hzga-mysql:
  28. build:
  29. context: ./database
  30. dockerfile: Dockerfile
  31. image: ataola/hzga-mysql:0.0.1
  32. ports:
  33. - "3306:3306"
  34. networks:
  35. - net-hzga
  36. container_name: hzga-mysql
  37. restart: on-failure
  38. networks:
  39. net-hzga:
  40. driver: bridge

下面介紹下通過docker-compose管理

部署這套服務: docker-compose up -d

暫停這套服務: docker-compose pause

下線這套服務: docker-compose down

檢視相關的日誌: docker-compose logs, 後面可以跟容器名字

如果是docker的命令 可以用docker help檢視,如果是docker-compose的命令可以用docker-compose help檢視

docker-compose的介紹: https://docs.docker.com/compose/

優勢

部署很爽啊,配置檔案一寫,命令一敲,起! 包括後續的一些維護,重啟啊、暫停啊等等很方便,方便搭建相關的叢集,相關的環境(開發、測試、釋出)

劣勢

增加了學習成本。

心得感悟

這個專案到這裡,第一個初代版本算上OK了。我這邊也羅列了一些思考和問題供讀者們交流

網路安全

  • 讓使用者不能同時線上,儘可以在一端登入
  • 對於敏感資料,比如說身份證、手機號等等前後端的互動肯定是不能明文的,怎麼處理?
  • 對使用者多次密碼錯誤嘗試鎖定使用者

效能優化

  • SPA應用一個是白屏、一個是對SEO不友好,假設這邊要處理的話,怎麼去做?
  • 假如資料量很大了,資料庫怎麼優化,或者查詢怎麼優化?
  • 加入使用者量很大的話,如何接入redis做持久化?

業務優化

  • 前端的相關表單加入詳細的格式校驗
  • 後端的引數加入詳細的格式校驗
  • 整理完備的電話號碼段資料庫、銀行卡號資料庫等等,進一步優化,各機構角色使用者只能看自己的(參考警情)
  • 相關的定時任務能不能手動停掉去,或者做出可配置化
  • 前端的相關下拉框做成可搜尋,優化使用者體驗
  • 前端的表格做的花裡胡哨,紅黃綠啥的安排下,讓使用者更直觀地看到狀態和操作

程式碼優化

  • 前端針對圖表封裝相應的元件
  • 文中所示的表格其實並不是通用性的,還是具有特定場景的,在這個基礎上改造一個通用性的元件

寫在最後

docker映象地址

反欺詐系統前端: https://hub.docker.com/repository/docker/ataola/hzga-fe

反欺詐系統後端: https://hub.docker.com/repository/docker/ataola/hzga-be

反欺詐系統MySQL: https://hub.docker.com/repository/docker/ataola/hzga-mysql

原始碼地址

github: https://github.com/cnroadbridge/anti-fraud-system

gitee: https://gitee.com/taoge2021/anti-fraud-system

假如人與人之間多一點真誠,少一些欺騙,那麼就不需要我們新生代農民工開發什麼反欺詐系統了,世界將會變得更美好,烏拉!烏拉!烏拉!

以上就是今天的全部內容,因為內容比較多,寫的也比較倉促,所以有些地方我也是潦草地一筆帶過,如有問題,歡迎與我交流探討,謝謝!