feat: init

This commit is contained in:
陶林 2023-09-01 16:03:20 +08:00
commit ad6cc0747b
23 changed files with 5729 additions and 0 deletions

11
.editorconfig Normal file
View File

@ -0,0 +1,11 @@
# 🎨 editorconfig.org
root = true
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
insert_final_newline = true

7
.eslintrc.json Normal file
View File

@ -0,0 +1,7 @@
{
"extends": "./node_modules/mwts/",
"ignorePatterns": ["node_modules", "dist", "test", "jest.config.js", "typings"],
"env": {
"jest": true
}
}

15
.gitignore vendored Normal file
View File

@ -0,0 +1,15 @@
logs/
npm-debug.log
yarn-error.log
node_modules/
package-lock.json
yarn.lock
coverage/
dist/
.idea/
run/
.DS_Store
*.sw*
*.un~
.tsbuildinfo
.tsbuildinfo.*

3
.prettierrc.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = {
...require('mwts/.prettierrc.json')
}

29
README.md Normal file
View File

@ -0,0 +1,29 @@
# my_midway_project
## QuickStart
<!-- add docs here for user -->
see [midway docs][midway] for more detail.
### Development
```bash
$ npm i
$ npm run dev
$ open http://localhost:7001/
```
### Deploy
```bash
$ npm start
```
### npm scripts
- Use `npm run lint` to check code style.
- Use `npm test` to run unit test.
[midway]: https://midwayjs.org

29
README.zh-CN.md Normal file
View File

@ -0,0 +1,29 @@
# my_midway_project
## 快速入门
<!-- 在此次添加使用文档 -->
如需进一步了解,参见 [midway 文档][midway]。
### 本地开发
```bash
$ npm i
$ npm run dev
$ open http://localhost:7001/
```
### 部署
```bash
$ npm start
```
### 内置指令
- 使用 `npm run lint` 来做代码风格检查。
- 使用 `npm test` 来执行单元测试。
[midway]: https://midwayjs.org

2
bootstrap.js vendored Normal file
View File

@ -0,0 +1,2 @@
const { Bootstrap } = require('@midwayjs/bootstrap');
Bootstrap.run();

6
jest.config.js Normal file
View File

@ -0,0 +1,6 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testPathIgnorePatterns: ['<rootDir>/test/fixtures'],
coveragePathIgnorePatterns: ['<rootDir>/test/'],
};

50
package.json Normal file
View File

@ -0,0 +1,50 @@
{
"name": "my-midway-project",
"version": "1.0.0",
"description": "",
"private": true,
"dependencies": {
"@midwayjs/bootstrap": "^3.12.3",
"@midwayjs/core": "^3.12.3",
"@midwayjs/decorator": "^3.12.3",
"@midwayjs/info": "^3.12.3",
"@midwayjs/koa": "^3.12.3",
"@midwayjs/logger": "^2.14.0",
"@midwayjs/validate": "^3.12.3"
},
"devDependencies": {
"@midwayjs/cli": "^2.0.0",
"@midwayjs/mock": "^3.12.3",
"@types/jest": "^29.2.0",
"@types/koa": "^2.13.4",
"@types/node": "14",
"cross-env": "^6.0.0",
"jest": "^29.2.2",
"mwts": "^1.0.5",
"ts-jest": "^29.0.3",
"typescript": "~4.8.0"
},
"engines": {
"node": ">=12.0.0"
},
"scripts": {
"start": "NODE_ENV=production node ./bootstrap.js",
"dev": "cross-env NODE_ENV=local midway-bin dev --ts",
"test": "midway-bin test --ts",
"cov": "midway-bin cov --ts",
"lint": "mwts check",
"lint:fix": "mwts fix",
"ci": "npm run cov",
"build": "midway-bin build -c"
},
"midway-bin-clean": [
".vscode/.tsbuildinfo",
"dist"
],
"repository": {
"type": "git",
"url": ""
},
"author": "anonymous",
"license": "MIT"
}

5367
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
import { MidwayConfig } from '@midwayjs/core';
export default {
// use for cookie sign key, should change to your own and keep security
keys: '1693555233471_3819',
koa: {
port: 7001,
},
} as MidwayConfig;

View File

@ -0,0 +1,7 @@
import { MidwayConfig } from '@midwayjs/core';
export default {
koa: {
port: null,
},
} as MidwayConfig;

31
src/configuration.ts Normal file
View File

@ -0,0 +1,31 @@
import { Configuration, App } from '@midwayjs/core';
import * as koa from '@midwayjs/koa';
import * as validate from '@midwayjs/validate';
import * as info from '@midwayjs/info';
import { join } from 'path';
// import { DefaultErrorFilter } from './filter/default.filter';
// import { NotFoundFilter } from './filter/notfound.filter';
import { ReportMiddleware } from './middleware/report.middleware';
@Configuration({
imports: [
koa,
validate,
{
component: info,
enabledEnvironment: ['local'],
},
],
importConfigs: [join(__dirname, './config')],
})
export class MainConfiguration {
@App('koa')
app: koa.Application;
async onReady() {
// add middleware
this.app.useMiddleware([ReportMiddleware]);
// add filter
// this.app.useFilter([NotFoundFilter, DefaultErrorFilter]);
}
}

View File

@ -0,0 +1,18 @@
import { Inject, Controller, Get, Query } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { UserService } from '../service/user.service';
@Controller('/api')
export class APIController {
@Inject()
ctx: Context;
@Inject()
userService: UserService;
@Get('/get_user')
async getUser(@Query('uid') uid) {
const user = await this.userService.getUser({ uid });
return { success: true, message: 'OK', data: user };
}
}

View File

@ -0,0 +1,9 @@
import { Controller, Get } from '@midwayjs/core';
@Controller('/')
export class HomeController {
@Get('/')
async home(): Promise<string> {
return 'Hello Midwayjs!';
}
}

View File

@ -0,0 +1,13 @@
import { Catch } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
@Catch()
export class DefaultErrorFilter {
async catch(err: Error, ctx: Context) {
// 所有的未分类错误会到这里
return {
success: false,
message: err.message,
};
}
}

View File

@ -0,0 +1,10 @@
import { Catch, httpError, MidwayHttpError } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
@Catch(httpError.NotFoundError)
export class NotFoundFilter {
async catch(err: MidwayHttpError, ctx: Context) {
// 404 错误会到这里
ctx.redirect('/404.html');
}
}

6
src/interface.ts Normal file
View File

@ -0,0 +1,6 @@
/**
* @description User-Service parameters
*/
export interface IUserOptions {
uid: number;
}

View File

@ -0,0 +1,27 @@
import { Middleware, IMiddleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';
@Middleware()
export class ReportMiddleware implements IMiddleware<Context, NextFunction> {
resolve() {
return async (ctx: Context, next: NextFunction) => {
// 控制器前执行的逻辑
const startTime = Date.now();
// 执行下一个 Web 中间件,最后执行到控制器
// 这里可以拿到下一个中间件或者控制器的返回值
const result = await next();
// 控制器之后执行的逻辑
ctx.logger.info(
`Report in "src/middleware/report.middleware.ts", rt = ${
Date.now() - startTime
}ms`
);
// 返回给上一个中间件的结果
return result;
};
}
static getName(): string {
return 'report';
}
}

View File

@ -0,0 +1,14 @@
import { Provide } from '@midwayjs/core';
import { IUserOptions } from '../interface';
@Provide()
export class UserService {
async getUser(options: IUserOptions) {
return {
uid: options.uid,
username: 'mockedName',
phone: '12345678901',
email: 'xxx.xxx@xxx.com',
};
}
}

View File

@ -0,0 +1,20 @@
import { createApp, close, createHttpRequest } from '@midwayjs/mock';
import { Framework } from '@midwayjs/koa';
describe('test/controller/home.test.ts', () => {
it('should POST /api/get_user', async () => {
// create app
const app = await createApp<Framework>();
// make request
const result = await createHttpRequest(app).get('/api/get_user').query({ uid: 123 });
// use expect by jest
expect(result.status).toBe(200);
expect(result.body.message).toBe('OK');
// close app
await close(app);
});
});

View File

@ -0,0 +1,21 @@
import { createApp, close, createHttpRequest } from '@midwayjs/mock';
import { Framework } from '@midwayjs/koa';
describe('test/controller/home.test.ts', () => {
it('should GET /', async () => {
// create app
const app = await createApp<Framework>();
// make request
const result = await createHttpRequest(app).get('/');
// use expect by jest
expect(result.status).toBe(200);
expect(result.text).toBe('Hello Midwayjs!');
// close app
await close(app);
});
});

25
tsconfig.json Normal file
View File

@ -0,0 +1,25 @@
{
"compileOnSave": true,
"compilerOptions": {
"target": "es2018",
"module": "commonjs",
"moduleResolution": "node",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"inlineSourceMap":true,
"noImplicitThis": true,
"noUnusedLocals": true,
"stripInternal": true,
"skipLibCheck": true,
"pretty": true,
"declaration": true,
"forceConsistentCasingInFileNames": true,
"typeRoots": [ "./typings", "./node_modules/@types"],
"outDir": "dist"
},
"exclude": [
"dist",
"node_modules",
"test"
]
}