Commit b0a231b6 authored by huanglu's avatar huanglu

feat: update

parents
'use strict';
module.exports = {
write: true,
plugin: 'autod-egg',
prefix: '^',
devprefix: '^',
exclude: [
'test/fixtures',
'coverage',
],
dep: [
'egg',
'egg-scripts',
],
devdep: [
'autod',
'autod-egg',
'egg-bin',
'tslib',
'typescript',
],
keep: [
],
semver: [
],
test: 'scripts',
};
**/*.d.ts
node_modules/
{
"extends": "eslint-config-egg/typescript",
"parserOptions": {
"project": "./tsconfig.json"
}
}
\ No newline at end of file
# 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: [ master ]
pull_request:
branches: [ master ]
schedule:
- cron: '0 2 * * *'
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
node-version: [8]
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@v1
with:
node-version: ${{ matrix.node-version }}
- name: Install Dependencies
run: npm i -g npminstall && npminstall
- name: Continuous Integration
run: npm run ci
- name: Code Coverage
uses: codecov/codecov-action@v1
with:
token: ${{ secrets.CODECOV_TOKEN }}
logs/
npm-debug.log
node_modules/
coverage/
.idea/
run/
logs/
.DS_Store
.vscode
*.swp
*.lock
*.js
!.autod.conf.js
app/**/*.js
test/**/*.js
config/**/*.js
app/**/*.map
test/**/*.map
config/**/*.map
language: node_js
node_js:
- '8'
before_install:
- npm i npminstall -g
install:
- npminstall
script:
- npm run ci
after_script:
- npminstall codecov && codecov
# hackernews-async-ts
[Hacker News](https://news.ycombinator.com/) showcase using typescript && egg
## QuickStart
### Development
```bash
$ npm i
$ npm run dev
$ open http://localhost:7001/
```
Don't tsc compile at development mode, if you had run `tsc` then you need to `npm run clean` before `npm run dev`.
### Deploy
```bash
$ npm run tsc
$ npm start
```
### Npm Scripts
- Use `npm run lint` to check code style
- Use `npm test` to run unit test
- se `npm run clean` to clean compiled js at development mode once
### Requirement
- Node.js 8.x
- Typescript 2.8+
import { Application } from 'egg';
export default (app: Application) => {
const { router } = app;
router.post('/account/login', app.controller.account.login);
};
import { Controller } from 'egg';
export default class extends Controller {
async login() {
const { ctx } = this;
const result = await ctx.service.account.login();
ctx.body = result;
}
}
import { Controller } from 'egg';
export default class HomeController extends Controller {
public async index() {
const { ctx } = this;
ctx.body = await ctx.service.home.sayHi('egg');
}
}
import { Controller } from 'egg';
export default class HomeController extends Controller {
public async list() {
const { ctx } = this;
const data = await ctx.service.news.list();
await this.ctx.render('list.nj', data);
}
}
export default {
parseMsg(action: string, payload = {}, metadata = {}) {
const meta = Object.assign({}, {
timestamp: Date.now(),
}, metadata);
return {
meta,
data: {
action,
payload,
},
};
},
};
import { Controller } from 'egg';
export default class NspController extends Controller {
async send() {
const { ctx, app } = this;
const nsp = app.io.of('/') as any;
const message = ctx.args[0] || {};
const socket = ctx.socket;
const client = socket.id;
try {
const { target, payload } = message;
if (!target) return;
const msg = ctx.helper.parseMsg('exchange', payload, { client, target });
nsp.sockets[target].emit('msg', msg);
} catch (error) {
app.logger.error(error);
}
}
async chatList() {
const { ctx, app } = this;
const nsp = app.io.of('/') as any;
const message = ctx.args[0] || {};
const socket = ctx.socket;
try {
const { target } = message;
if (!target) return;
socket.emit('msg', nsp.sockets);
} catch (error) {
app.logger.error(error);
}
}
}
import { Context } from 'egg';
export default () => {
return async (_ctx: Context, next: any) => {
const { app } = _ctx;
const nsp = app.io.of('/') as any;
nsp.emit('updateList', nsp.sockets);
await next();
console.log('disconnection!');
nsp.emit('updateList', nsp.sockets);
};
};
import { Context } from 'egg';
export default () => {
return async (ctx: Context, next: any) => {
ctx.socket.emit('res', 'packet received!');
console.log('packet:', ctx.packet);
await next();
};
};
import { Application } from 'egg';
import accountRouter from './account-router';
import socketRouter from './socket-router';
export default (app: Application) => {
const { controller, router } = app;
router.get('/', controller.home.index);
accountRouter(app);
socketRouter(app);
};
import { Service } from 'egg';
export default class extends Service {
async login() {
const { ctx, app, config } = this;
const { request } = ctx;
const body = request.body;
const { username, password } = body || {};
const result = await app.curl(config.sourceUrl + 'service-user/auth/employee', {
method: 'POST',
data: {
account: username,
assistant: false,
identityType: 1,
ip: '0.0.0.0',
password,
type: 'employee',
},
contentType: 'json',
dataType: 'json',
});
if (result.status >= 200 && result.status <= 299 && result.data.code === 0) {
const bussinessData = result.data || {};
const { data = {} } = bussinessData;
const info = await app.curl(config.sourceUrl + 'service-user/employees/info', {
headers: {
Authorization: `Bearer ${data.token || ''}`,
},
dataType: 'json',
contentType: 'json',
});
if (info.status >= 200 && info.status <= 299 && info.data.code === 0) {
return {
data: {
token: data.token || '',
...(info.data || {}).data || {},
},
code: 0,
};
}
}
return {
code: 100,
msg: 'error',
data: null,
};
}
}
import { Service } from 'egg';
/**
* Test Service
*/
export default class Test extends Service {
public async sayHi(name: string) {
return `hi, ${name}`;
}
}
import { Application } from 'egg';
export default (app: Application) => {
const { io } = app;
io.of('/').route('msg', (io.controller as any).nsp.send);
io.of('/').route('chatList', (io.controller as any).nsp.chatList);
};
<html>
<head>
<title>Hacker News</title>
<link rel="stylesheet" href="/public/css/news.css" />
</head>
<body>
<ul class="news-view view">
<span>list: {{ data }}</span>
</ul>
</body>
</html>
\ No newline at end of file
environment:
matrix:
- nodejs_version: '8'
install:
- ps: Install-Product node $env:nodejs_version
- npm i npminstall && node_modules\.bin\npminstall
test_script:
- node --version
- npm --version
- npm run test
build: off
import { EggAppConfig, EggAppInfo, PowerPartial, Request } from 'egg';
import * as qs from 'qs';
const redisConfig = {
host: '192.168.32.34',
port: 6379,
password: '123456',
};
export default (appInfo: EggAppInfo) => {
const config = {} as PowerPartial<EggAppConfig>;
config.keys = appInfo.name + '_1607088260928_8707';
config.middleware = [];
const bizConfig = {
sourceUrl: 'https://geek.jkwljy.com/',
};
const view = {
defaultViewEngine: 'nunjucks',
mapping: {
'.nj': 'nunjucks',
},
};
const io = {
init: { wsEngine: 'ws' },
namespace: {
'/': {
connectionMiddleware: [ 'auth' ], // 通常在这一步进行授权认证,对认证失败的客户端做出相应的处理
packetMiddleware: [ 'packet' ], // 针对消息的处理
},
},
generateId: (req: Request) => { // 自定义 socket.id 生成函数
const data = qs.parse(req.url.split('?')[1]);
return data.userId;
},
redis: {
...redisConfig,
},
};
const redis = {
client: {
...redisConfig,
db: 0,
},
};
const cors = {
origin: '*',
credentials: true,
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
};
return {
...config,
...bizConfig,
view,
io,
redis,
cors,
security: {
csrf: {
enable: false,
},
},
};
};
import { EggAppConfig, PowerPartial } from 'egg';
export default () => {
const config: PowerPartial<EggAppConfig> = {};
return config;
};
import { EggAppConfig, PowerPartial } from 'egg';
export default () => {
const cluster = {
listen: {
port: 7001,
hostname: '0,0,0,0', // 不建议设置 hostname 为 '0.0.0.0',它将允许来自外部网络和来源的连接,请在知晓风险的情况下使用
},
};
const config: PowerPartial<EggAppConfig> = {
cluster,
};
return config;
};
import { EggPlugin } from 'egg';
const plugin: EggPlugin = {
nunjucks: {
enable: true,
package: 'egg-view-nunjucks',
},
io: {
enable: true,
package: 'egg-socket.io',
},
redis: {
enable: true,
package: 'egg-redis',
},
cors: {
enable: true,
package: 'egg-cors',
},
};
export default plugin;
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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