const fs = require('fs') const path = require('path') const Koa = require('koa') const Router = require('koa-router') const bodyParser = require('koa-bodyparser') const LRU = require('lru-cache') const WebSocket = require('ws') const koaStatic = require('koa-static') const routerOptions = { prefix: '/api' } const lruOptions = { max: 50, maxAge: 1000 * 60 * 60 * 24 } const dataPath = './data/data.json' const staticPath = './dist' const router = new Router(routerOptions) const cache = new LRU(lruOptions) let STATIC_DATA = '' fs.readFile(dataPath, (err, buf) => { if (err) { console.error(err) return } STATIC_DATA = buf.toString() }) const app = new Koa() const wss = new WebSocket.Server({ port: 5556 }) app.use(koaStatic(path.join(__dirname, staticPath))) wss.on('connection', ws => { ws.on('message', msg => { const res = JSON.parse(msg) console.log('msg: ', res) if (res.code && res.status === 'update') { const list = cache.get(res.code) const data = JSON.stringify({ data: list }) wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) { client.send(data) } }) } }) }) app.use(bodyParser()) // 判断是不是api // app.use((ctx, next) => { // const url = ctx.url // const isApi = /^\/api/.test(url) // ctx.$isApi = isApi // next() // }) router.get('/list', (ctx, next) => { const { code } = ctx.query let data if (cache.has(code)) { data = cache.get(code) } else { const jsonData = JSON.parse(STATIC_DATA).data || [] const len = 25 const sum = jsonData.length - len const arr = new Array(25).fill(1).map(el => Math.floor(Math.random() * sum)) 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] data = new Array(25).fill(1).map((el, i) => { const del = groupList.length ? Math.floor(Math.random() * groupList.length) : 0 const group = groupList.splice(del, 1)[0] return { text: jsonData.splice(arr[i], 1)[0], status: 0, group } }) cache.set(code, data) } ctx.body = { code, data } }) router.put('/status/:code', ctx => { const { params, request } = ctx const { code } = params const { index } = request.body const list = cache.get(code) || [] if (!index) { throw new Error('index is not find') } if (!list || !list.length) { throw new Error('cache list is not find') } list[index].status = list[index].status ? 0 : 1 cache.set(code, list) ctx.body = { success: true, msg: '更新成功', data: list[index] } }) app.use(router.routes()).use(router.allowedMethods()) app.on('error', err => console.error(err)) app.listen(5555) console.log('http://127.0.0.1:5555')