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.
{
"name": "geek-egg-websocket",
"version": "1.0.0",
"description": "egg 实践",
"private": true,
"egg": {
"typescript": true,
"declarations": true
},
"scripts": {
"start": "npm run tsc && egg-scripts start --daemon --title=egg-server-geek-egg",
"stop": "egg-scripts stop --title=egg-server-geek-egg",
"dev": "egg-bin dev --sticky",
"debug": "egg-bin debug",
"test-local": "egg-bin test",
"test": "npm run lint -- --fix && npm run test-local",
"cov": "egg-bin cov",
"tsc": "ets && tsc -p tsconfig.json",
"ci": "npm run lint && npm run cov && npm run tsc",
"autod": "autod",
"lint": "eslint . --ext .ts",
"clean": "ets clean"
},
"dependencies": {
"egg": "^2.6.1",
"egg-cors": "^2.2.3",
"egg-redis": "^2.4.0",
"egg-scripts": "^2.6.0",
"egg-socket.io": "^4.1.6",
"egg-view-nunjucks": "^2.2.0",
"qs": "^6.9.4"
},
"devDependencies": {
"@types/mocha": "^2.2.40",
"@types/node": "^7.0.12",
"@types/supertest": "^2.0.0",
"autod": "^3.0.1",
"autod-egg": "^1.1.0",
"egg-bin": "^4.11.0",
"egg-ci": "^1.8.0",
"egg-mock": "^3.16.0",
"eslint": "^6.7.2",
"eslint-config-egg": "^8.0.0",
"tslib": "^1.9.0",
"typescript": "^3.0.0"
},
"engines": {
"node": ">=8.9.0"
},
"ci": {
"version": "8"
},
"repository": {
"type": "git",
"url": ""
},
"eslintIgnore": [
"coverage"
],
"author": "huanglu",
"license": "MIT"
}
import * as assert from 'assert';
import { app } from 'egg-mock/bootstrap';
describe('test/app/controller/home.test.ts', () => {
it('should GET /', async () => {
const result = await app.httpRequest().get('/').expect(200);
assert(result.text === 'hi, egg');
});
});
import * as assert from 'assert';
import { Context } from 'egg';
import { app } from 'egg-mock/bootstrap';
describe('test/app/service/Test.test.js', () => {
let ctx: Context;
before(async () => {
ctx = app.mockContext();
});
it('sayHi', async () => {
const result = await ctx.service.test.sayHi('egg');
assert(result === 'hi, egg');
});
});
{
"compileOnSave": true,
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"strict": true,
"noImplicitAny": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"charset": "utf8",
"allowJs": false,
"pretty": true,
"noEmitOnError": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"strictPropertyInitialization": false,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"inlineSourceMap": true,
"importHelpers": true
},
"exclude": [
"app/public",
"app/views",
"node_modules*"
]
}
// This file is created by egg-ts-helper@1.25.8
// Do not modify this file!!!!!!!!!
import 'egg';
import ExportAccount from '../../../app/controller/account';
import ExportHome from '../../../app/controller/home';
import ExportNews from '../../../app/controller/news';
declare module 'egg' {
interface IController {
account: ExportAccount;
home: ExportHome;
news: ExportNews;
}
}
// This file is created by egg-ts-helper@1.25.8
// Do not modify this file!!!!!!!!!
import 'egg';
import ExtendIHelper from '../../../app/extend/helper';
type ExtendIHelperType = typeof ExtendIHelper;
declare module 'egg' {
interface IHelper extends ExtendIHelperType { }
}
\ No newline at end of file
// This file is created by egg-ts-helper@1.25.8
// Do not modify this file!!!!!!!!!
import 'egg';
export * from 'egg';
export as namespace Egg;
// This file is created by egg-ts-helper@1.25.8
// Do not modify this file!!!!!!!!!
import 'egg';
type AnyClass = new (...args: any[]) => any;
type AnyFunc<T = any> = (...args: any[]) => T;
type CanExportFunc = AnyFunc<Promise<any>> | AnyFunc<IterableIterator<any>>;
type AutoInstanceType<T, U = T extends CanExportFunc ? T : T extends AnyFunc ? ReturnType<T> : T> = U extends AnyClass ? InstanceType<U> : U;
import ExportAccount from '../../../app/service/account';
import ExportHome from '../../../app/service/home';
declare module 'egg' {
interface IService {
account: AutoInstanceType<typeof ExportAccount>;
home: AutoInstanceType<typeof ExportHome>;
}
}
// This file is created by egg-ts-helper@1.25.8
// Do not modify this file!!!!!!!!!
import 'egg';
import { EggAppConfig } from 'egg';
import ExportConfigDefault from '../../config/config.default';
type ConfigDefault = ReturnType<typeof ExportConfigDefault>;
type NewEggAppConfig = ConfigDefault;
declare module 'egg' {
interface EggAppConfig extends NewEggAppConfig { }
}
\ No newline at end of file
// This file is created by egg-ts-helper@1.25.8
// Do not modify this file!!!!!!!!!
import 'egg';
import 'egg-onerror';
import 'egg-session';
import 'egg-i18n';
import 'egg-watcher';
import 'egg-multipart';
import 'egg-security';
import 'egg-development';
import 'egg-logrotator';
import 'egg-schedule';
import 'egg-static';
import 'egg-jsonp';
import 'egg-view';
import 'egg-view-nunjucks';
import 'egg-socket.io';
import 'egg-redis';
import 'egg-cors';
import { EggPluginItem } from 'egg';
declare module 'egg' {
interface EggPlugin {
onerror?: EggPluginItem;
session?: EggPluginItem;
i18n?: EggPluginItem;
watcher?: EggPluginItem;
multipart?: EggPluginItem;
security?: EggPluginItem;
development?: EggPluginItem;
logrotator?: EggPluginItem;
schedule?: EggPluginItem;
static?: EggPluginItem;
jsonp?: EggPluginItem;
view?: EggPluginItem;
nunjucks?: EggPluginItem;
io?: EggPluginItem;
redis?: EggPluginItem;
cors?: EggPluginItem;
}
}
\ No newline at end of file
import 'egg';
declare module 'egg' {
}
\ No newline at end of file
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