Commit dfd8dcc3 authored by huanglu's avatar huanglu

feat: 初始化egg模板

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 ]
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
node-version: [8.x]
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm i -g npminstall && npminstall
- run: npm run ci
env:
CI: true
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
yarn.lock
language: node_js
node_js:
- '8'
before_install:
- npm i npminstall -g
install:
- npminstall
script:
- npm run ci
after_script:
- npminstall codecov && codecov
{
"types": ["feat", "fix", "docs", "style", "refactor", "perf", "test", "chore"],
"scope": {
"required": false,
"allowed": ["*"],
"validate": false,
"multiple": false
},
"warnOnFail": false,
"maxSubjectLength": 100,
"subjectPattern": ".+",
"subjectPatternErrorMsg": "",
"helpMessage": "",
"autoFix": false
}
\ No newline at end of file
# hackernews-async-ts
[Hacker News](https://news.ycombinator.com/) showcase using typescript && egg
### Requirement
- Node.js 8.x
- Typescript 2.8+
### 中间件
-
### 模板渲染 egg-view-nunjucks
### helpers
import { Controller } from 'egg';
/**
* @Controller home
*/
export default class HomeController extends Controller {
public async index() {
const { ctx } = this;
await ctx.service.account.index();
}
public async login() {
const { ctx } = this;
await ctx.service.account.login();
}
}
/* eslint-disable @typescript-eslint/no-unused-vars */
import moment = require('moment');
import querystring = require('querystring');
export default {
formatTime: (time: Date) => moment(time).format('YYYY-MM-DD HH:mm:ss'),
// 处理成功响应
success({ res = null, msg = '请求成功' }) {
(this as any).ctx.body = {
code: 0,
data: res,
msg,
};
(this as any).status = 200;
},
// 封装httpclient
http(_config = {}) {
return {
get: async (url: string, params: any = {}, options = {}) => {
const queryString = querystring.stringify(params);
const data = (this as any).ctx.curl(`${url}?${queryString}`, {
// 明确告诉 HttpClient 以 JSON 格式处理返回的响应 body
dataType: 'json',
...options,
});
return data;
},
post: async (url: string, params: any, options = {}) => {
const data = await (this as any).ctx.curl(url, {
method: 'POST',
contentType: 'json',
data: {
...params,
},
dataType: 'json',
...options,
});
return data;
},
};
},
};
import { Context } from 'egg';
module.exports = () => {
return async function errorHandler(ctx: Context, next: Function) {
await next();
const { status } = ctx;
if (status === 404) {
if (ctx.acceptJSON) {
ctx.body = {
code: 404,
message: '404',
};
ctx.status = 200;
return;
}
ctx.body = '<h1>访问路径不存在</h1>';
}
};
};
import { Context } from 'egg';
module.exports = (options: any) => {
return async function jwtErr(ctx: Context, next: Function) {
const { request, path } = ctx;
const token = request.header.authorization;
let decode = '';
if (token) {
try {
// 解码token
decode = ctx.app.jwt.verify(token, options.secret);
console.log('decode======>', decode);
} catch (error) {
ctx.status = 401;
ctx.body = {
message: error.message,
};
return;
}
} else {
if (/\/api/g.test(path)) {
ctx.status = 200;
ctx.body = {
message: '没有token',
code: 404,
};
return;
}
await next();
}
};
};
import { Application } from 'egg';
// import home from './routers/home';
// import homeRouter from './routers/home';
export default (app: Application) => {
const { controller } = app;
app.get('/', controller.home.index);
app.post('/login', controller.home.login);
};
import { Application } from 'egg';
export default (app: Application, path = '/home') => {
const { router, controller } = app;
const homeRouter = router.namespace(path);
homeRouter.get('', controller.home.index);
};
import { Service } from 'egg';
export default class Account extends Service {
public async login() {
const { ctx } = this;
// const sourceUrl = config.source_url;
const result = await ctx.helper.http().get('https://registry.npm.taobao.org/egg/latest');
ctx.body = result;
}
public async index() {
const { ctx } = this;
// const headers = {
// 'Content-Type': 'text/html',
// };
// ctx.set(headers);
await ctx.render('login.html');
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{% block header %}
This is the default content
{% endblock %}
<section class="left">
{% block left %}{% endblock %}
</section>
<section class="right">
{% block right %}
{% endblock %}
</section>
</body>
</html>
\ No newline at end of file
{% extends "./base.html" %}
{% block header %}
<form action="logisn" method="POST" accept="*" enctype="application/x-www-form-urlencoded">
<input name="name" type="text" /><br>
<input type="number" name='age'><br>
<input type="submit" title="submit" />
</form>
{% endblock %}
\ 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 } from 'egg';
export default (appInfo: EggAppInfo) => {
const config = {} as PowerPartial<EggAppConfig>;
config.keys = appInfo.name + '_1593343282720_1061';
const bizConfig = {
view: {
defaultViewEngine: 'nunjucks',
mapping: {
'.html': 'nunjucks',
},
cache: false,
trimBlocks: true,
lstripBlocks: true,
},
source_url: 'https://registry.npm.taobao.org',
};
config.jwt = { // jwt配置项
secret: '123456',
};
config.middleware = [ 'errorHandler', 'jwtHandler' ];
return {
...config,
...bizConfig,
};
};
import { EggAppConfig, PowerPartial } from 'egg';
console.log('==== env : dev =====');
export default () => {
const config: PowerPartial<EggAppConfig> = {};
config.swaggerdoc = {
dirScanner: './app/controller',
apiInfo: {
title: 'egg-swagger',
description: 'swagger-ui for egg',
version: '1.0.0',
},
schemes: [ 'http', 'https' ],
consumes: [ 'application/json' ],
produces: [ 'application/json' ],
securityDefinitions: {
},
enableSecurity: false,
// enableValidate: true,
routerMap: false,
enable: true,
};
return config;
};
import { EggAppConfig, PowerPartial } from 'egg';
export default () => {
const config: PowerPartial<EggAppConfig> = {};
return config;
};
import { EggAppConfig, PowerPartial } from 'egg';
export default () => {
const config: PowerPartial<EggAppConfig> = {};
return config;
};
import { EggPlugin } from 'egg';
const plugin: EggPlugin = {
nunjucks: {
enable: true,
package: 'egg-view-nunjucks',
},
routerPlus: {
enable: true,
package: 'egg-router-plus',
},
jwt: {
enable: false,
package: 'egg-jwt',
},
};
export default plugin;
{
"name": "geek-egg-template",
"version": "1.0.0",
"description": "极客数学egg项目模板",
"private": true,
"egg": {
"typescript": true,
"declarations": true
},
"scripts": {
"start": "egg-scripts start --daemon --title=egg-server-geek-egg-template",
"stop": "egg-scripts stop --title=egg-server-geek-egg-template",
"dev": "egg-bin dev",
"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-jwt": "^3.1.7",
"egg-router-plus": "^1.3.1",
"egg-scripts": "^2.6.0",
"egg-validate": "^2.0.2",
"egg-view-nunjucks": "^2.2.0",
"moment": "^2.27.0"
},
"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",
"egg-swagger-doc": "^2.3.2",
"eslint": "^6.7.2",
"eslint-config-egg": "^8.0.0",
"husky": "^4.2.5",
"tslib": "^1.9.0",
"typescript": "^3.0.0",
"validate-commit-msg": "^2.14.0"
},
"engines": {
"node": ">=8.9.0"
},
"ci": {
"version": "8"
},
"repository": {
"type": "git",
"url": ""
},
"eslintIgnore": [
"coverage"
],
"author": "huanglu",
"license": "MIT",
"husky": {
"hooks": {
"commit-msg": "validate-commit-msg"
}
}
}
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 ExportHome from '../../../app/controller/home';
declare module 'egg' {
interface IController {
home: ExportHome;
}
}
// 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';
import ExportErrorHandler from '../../../app/middleware/error-handler';
import ExportJwtHandler from '../../../app/middleware/jwt-handler';
declare module 'egg' {
interface IMiddleware {
errorHandler: typeof ExportErrorHandler;
jwtHandler: typeof ExportJwtHandler;
}
}
// 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';
declare module 'egg' {
interface IService {
account: AutoInstanceType<typeof ExportAccount>;
}
}
// 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-router-plus';
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;
routerPlus?: EggPluginItem;
jwt?: EggPluginItem;
}
}
\ No newline at end of file
import 'egg';
import { Application, Application } from 'egg';
declare module 'egg' {
interface Application {
jwt: any
}
}
\ 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