Commit 856759c8 authored by wuhao's avatar wuhao 🎯

send

parents
{
"extends": "eslint-config-egg",
"root": true
}
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
name: Node.js CI
on:
push:
branches:
- main
- master
pull_request:
branches:
- main
- master
schedule:
- cron: '0 2 * * *'
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
node-version: [16, 18]
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- name: Checkout Git Source
uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- name: Install Dependencies
run: npm i
- name: Continuous Integration
run: npm run ci
- name: Code Coverage
uses: codecov/codecov-action@v3
with:
token: ${{ secrets.CODECOV_TOKEN }}
logs/
npm-debug.log
yarn-error.log
node_modules/
*-lock.json
*-lock.yaml
yarn.lock
coverage/
.idea/
run/
.DS_Store
*.sw*
*.un~
typings/
.nyc_output/
.history
\ No newline at end of file
# socketio_middleware
## QuickStart
<!-- add docs here for user -->
see [egg docs][egg] for more detail.
### Development
```bash
$ npm i
$ npm run dev
$ open http://localhost:7001/
```
### Deploy
```bash
$ npm start
$ npm stop
```
### npm scripts
- Use `npm run lint` to check code style.
- Use `npm test` to run unit test.
- Use `npm run autod` to auto detect dependencies upgrade, see [autod](https://www.npmjs.com/package/autod) for more detail.
[egg]: https://eggjs.org
\ No newline at end of file
'use strict';
const { Controller } = require('egg');
class HomeController extends Controller {
async index() {
const { ctx } = this;
ctx.body = 'hi, egg';
}
async postmsg() {
const { ctx, app } = this;
console.log(ctx.request.body, '111111');
const { id, msg } = ctx.request.body;
if (!id) {
ctx.body = {
code: 0,
success: true,
data: ctx.request.body,
};
return;
}
const clients = app.io.sockets.sockets;
// query中的id为 用户id io可以直接emit
Object.values(clients)?.map(io => {
const index = id.indexOf(io?.handshake?.query?.id);
if (Array.isArray(id) && index !== -1) {
io.emit('message', msg);
} else if (io?.handshake?.query?.id === id) {
io.emit('message', msg);
}
return io;
});
ctx.body = {
code: 0,
success: true,
data: ctx.request.body,
};
}
}
module.exports = HomeController;
/* eslint-disable no-unused-vars */
'use strict';
const Controller = require('egg').Controller;
class ChatController extends Controller {
async message() {
const { ctx, app, socket } = this;
const message = ctx.args[0];
console.log('Received message:', message);
const clients = app.io.sockets.sockets;
// query中的id为 用户id io可以直接emit
console.log(Object.values(clients)?.map((io, i) => {
io.emit('message', message);
return io;
}));
}
}
module.exports = ChatController;
'use strict';
const onlineUsers = {};
module.exports = () => {
return async (ctx, next) => {
const { socket, app } = ctx;
const { io } = app;
const nsp = io.of('/');
onlineUsers[socket.handshake.query.id] = {
userId: socket.handshake.query.id,
};
setTimeout(() => {
nsp.emit('onlineUsers', Object.keys(onlineUsers));
}, 1000);
socket.on('disconnect', () => {
delete onlineUsers[socket.handshake.query.id];
nsp.emit('onlineUsers', Object.keys(onlineUsers));
});
await next();
};
};
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller, io } = app;
router.get('/', controller.home.index);
router.post('/postmsg', controller.home.postmsg);
io.of('/').route('message', io.controller.chat.message);
};
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = (exports = {});
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1684983472866_2862';
// add your middleware config here
config.middleware = [];
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
// cros允许请求
config.security = {
csrf: {
enable: false,
},
domainWhiteList: [ '*' ], // 允许访问域名的白名单,*表示都能访问
};
config.cors = {
origin: '*',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
credentials: true,
};
// socket.io
config.io = {
init: {
wsEngine: 'ws',
}, // passed to engine.io
namespace: {
'/': {
connectionMiddleware: [ 'connection' ],
packetMiddleware: [],
},
},
redis: {
host: 'localhost',
port: 6379,
// auth_pass: '123456',
// db: 0,
},
};
return {
...config,
...userConfig,
};
};
'use strict';
// socket.io
exports.io = {
enable: true,
package: 'egg-socket.io',
};
{
"include": [
"**/*"
]
}
\ No newline at end of file
{
"name": "socketio_middleware",
"version": "1.0.0",
"description": "",
"private": true,
"egg": {
"declarations": true
},
"dependencies": {
"egg": "^3",
"egg-scripts": "^2",
"egg-socket.io": "^4.1.6"
},
"devDependencies": {
"egg-bin": "^5",
"egg-ci": "^2",
"egg-mock": "^5",
"eslint": "^8",
"eslint-config-egg": "^12"
},
"engines": {
"node": ">=16.0.0"
},
"scripts": {
"start": "egg-scripts start --daemon --title=egg-server-socketio_middleware",
"stop": "egg-scripts stop --title=egg-server-socketio_middleware",
"dev": "egg-bin dev --sticky",
"debug": "egg-bin debug",
"test": "npm run lint -- --fix && npm run test-local",
"test-local": "egg-bin test",
"cov": "egg-bin cov",
"lint": "eslint .",
"ci": "npm run lint && npm run cov"
},
"ci": {
"version": "16, 18",
"type": "github"
},
"repository": {
"type": "git",
"url": ""
},
"author": "wuhao",
"license": "MIT"
}
'use strict';
const { app, assert } = require('egg-mock/bootstrap');
describe('test/app/controller/home.test.js', () => {
it('should assert', async () => {
const pkg = require('../../../package.json');
assert(app.config.keys.startsWith(pkg.name));
// const ctx = app.mockContext({});
// yield ctx.service.xx();
});
it('should GET /', async () => {
return app.httpRequest()
.get('/')
.expect('hi, egg')
.expect(200);
});
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment