server.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. const fs = require('fs')
  2. const path = require('path')
  3. const Koa = require('koa')
  4. const Router = require('koa-router')
  5. const bodyParser = require('koa-bodyparser')
  6. const LRU = require('lru-cache')
  7. const WebSocket = require('ws')
  8. const koaStatic = require('koa-static')
  9. const routerOptions = {
  10. prefix: '/api'
  11. }
  12. const lruOptions = {
  13. max: 50,
  14. maxAge: 1000 * 60 * 60 * 24
  15. }
  16. const watchFileOptions = {
  17. interval: 60 * 10e2
  18. }
  19. const dataPath = './data/data.txt'
  20. const reviewDataPath = './data/reviewData.txt'
  21. const staticPath = './dist'
  22. const router = new Router(routerOptions)
  23. const cache = new LRU(lruOptions)
  24. let STATIC_DATA = ''
  25. fs.readFile(dataPath, (err, buf) => {
  26. if (err) {
  27. console.error(err)
  28. return
  29. }
  30. STATIC_DATA = buf.toString().replace('\n', '')
  31. })
  32. fs.watchFile(dataPath, watchFileOptions, (curr, prev) => {
  33. if (curr.mtime !== prev.mtime) {
  34. STATIC_DATA = ''
  35. fs.readFile(dataPath, (err, buf) => {
  36. if (err) {
  37. console.error(err)
  38. return
  39. }
  40. STATIC_DATA = buf.toString().split(',')
  41. })
  42. }
  43. })
  44. const app = new Koa()
  45. const wss = new WebSocket.Server({ port: 5556 })
  46. app.use(koaStatic(path.join(__dirname, staticPath)))
  47. wss.on('connection', ws => {
  48. ws.on('message', msg => {
  49. const res = JSON.parse(msg)
  50. console.log('msg: ', res)
  51. if (res.code) {
  52. const list = cache.get(res.code)
  53. if (res.status === 'update') {
  54. const data = JSON.stringify({ data: list })
  55. wss.clients.forEach(client => {
  56. if (client.readyState === WebSocket.OPEN) {
  57. client.send(data)
  58. }
  59. })
  60. } else if (res.status === 'over') {
  61. list.forEach(el => {
  62. el.status = 1
  63. })
  64. const data = JSON.stringify({ data: list })
  65. wss.clients.forEach(client => {
  66. if (client.readyState === WebSocket.OPEN) {
  67. client.send(data)
  68. }
  69. })
  70. }
  71. }
  72. })
  73. })
  74. app.use(bodyParser())
  75. // 判断是不是api
  76. // app.use((ctx, next) => {
  77. // const url = ctx.url
  78. // const isApi = /^\/api/.test(url)
  79. // ctx.$isApi = isApi
  80. // next()
  81. // })
  82. router.get('/list', (ctx, next) => {
  83. const { code } = ctx.query
  84. let data
  85. if (cache.has(code)) {
  86. data = cache.get(code)
  87. } else {
  88. const jsonData = STATIC_DATA || []
  89. const len = 25
  90. const sum = jsonData.length - len
  91. const arr = new Array(25).fill(1).map(el => Math.floor(Math.random() * sum))
  92. const groupList = [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 0, 0]
  93. data = new Array(25).fill(1).map((el, i) => {
  94. const del = groupList.length ? Math.floor(Math.random() * groupList.length) : 0
  95. const group = groupList.splice(del, 1)[0]
  96. return {
  97. text: jsonData.splice(arr[i], 1)[0],
  98. status: 0,
  99. group
  100. }
  101. })
  102. cache.set(code, data)
  103. }
  104. ctx.body = {
  105. code,
  106. data
  107. }
  108. })
  109. router.put('/status/:code', ctx => {
  110. const { params, request } = ctx
  111. const { code } = params
  112. const { index } = request.body
  113. const list = cache.get(code) || []
  114. if (!index && index !== 0) {
  115. throw new Error('index is not find')
  116. }
  117. if (!list || !list.length) {
  118. throw new Error('cache list is not find')
  119. }
  120. list[index].status = list[index].status ? 0 : 1
  121. cache.set(code, list)
  122. ctx.body = { success: true, msg: '更新成功', data: list[index] }
  123. })
  124. router.post('/words', ctx => {
  125. const { request } = ctx
  126. const { words = '' } = request.body
  127. const wordsList = words.split(',')
  128. const noExist = []
  129. const exist = wordsList.filter(el => {
  130. if (STATIC_DATA.indexOf(el) !== -1) {
  131. return true
  132. }
  133. noExist.push(el)
  134. return false
  135. })
  136. const pushNewWords = noExist.join(',')
  137. fs.appendFile(reviewDataPath, pushNewWords, (err) => {
  138. if (err) {
  139. console.error('appendFile error:', err)
  140. }
  141. })
  142. let body = {}
  143. if (exist.length) {
  144. body = { success: false, exist }
  145. } else {
  146. body = { success: true }
  147. }
  148. ctx.body = body
  149. })
  150. router.get('/reviews', ctx => {
  151. const buf = fs.readFileSync(reviewDataPath)
  152. const text = buf.toString()
  153. let list = []
  154. if (text) {
  155. list = text.split(',')
  156. }
  157. ctx.body = { success: true, list }
  158. })
  159. router.post('/reviews', ctx => {
  160. const { request } = ctx
  161. const { words = '' } = request.body
  162. const wordsList = words.split(',')
  163. const noExist = []
  164. const exist = wordsList.filter(el => {
  165. if (STATIC_DATA.indexOf(el) !== -1) {
  166. return true
  167. }
  168. if (el) {
  169. noExist.push(el)
  170. }
  171. return false
  172. })
  173. try {
  174. fs.appendFileSync(dataPath, `,${noExist.join(',')}`)
  175. fs.writeFile(reviewDataPath, '', err => {
  176. if (err) {
  177. return console.error('clear reviewData error:', err)
  178. }
  179. })
  180. if (exist.length) {
  181. ctx.body = { success: true, msg: `${exist.join(',')} 添加失败,词已存在` }
  182. } else {
  183. ctx.body = { success: true, msg: '添加成功' }
  184. }
  185. } catch (error) {
  186. console.error('appendFile error:', error)
  187. ctx.body = { success: false, msg: JSON.stringify(error) }
  188. }
  189. })
  190. app.use(router.routes()).use(router.allowedMethods())
  191. app.on('error', err => console.error(err))
  192. app.listen(5555)
  193. console.log('http://127.0.0.1:5555')