Compare commits

...

2 Commits

Author SHA1 Message Date
dev
fba22f7d30 fix: 新增ide配置 2022-11-15 09:30:22 +08:00
dev
2aa82ad988 feat: midway 2022-09-28 13:46:14 +08:00
24 changed files with 582 additions and 26 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
}
}

18
.gitignore vendored
View File

@ -1,3 +1,15 @@
/node_modules
/.next
src/.umi
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')
}

147
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,147 @@
// setting.json
{
"debug.console.fontFamily": "JetBrains Mono",
// debugAnyway:
"debug.onTaskErrors": "debugAnyway",
//
"editor.accessibilitySupport": "off",
//
"editor.cursorSmoothCaretAnimation": true,
"editor.find.addExtraSpaceOnTop": false,
//
"editor.fontLigatures": "'ss01', 'ss02', 'ss03', 'ss06', 'zero'",
//
"editor.glyphMargin": true,
//
"editor.inlineSuggest.enabled": true,
// 使
"editor.multiCursorModifier": "ctrlCmd",
"editor.tabSize": 2,
"editor.fontWeight": 440,
"editor.fontFamily": "JetBrains Mono, Menlo, Monaco, 'Courier New', monospace",
// ASCII
"editor.unicodeHighlight.ambiguousCharacters": false,
//
"editor.unicodeHighlight.invisibleCharacters": false,
// ESLint
"eslint.validate": [
"javascript",
"javascriptreact",
"vue",
"typescript",
"typescriptreact",
"html",
"css",
"scss",
"less",
"mpx",
"json",
"markdown"
],
// eslint
"eslint.quiet": true,
// eslint
"eslint.codeActionsOnSave.mode": "problems",
"eslint.format.enable": true,
//
"files.autoSaveDelay": 5000,
// LF
"files.eol": "\n",
//
"files.simpleDialog.enable": true,
// Git
"git.confirmSync": false,
"git.autofetch": true,
//
"security.workspace.trust.untrustedFiles": "open",
"vetur.validation.template": false,
//
"workbench.tree.indent": 10,
"workbench.iconTheme": "file-icons",
"workbench.startupEditor": "newUntitledFile",
"workbench.productIconTheme": "icons-carbon",
"workbench.colorTheme": "Community Material Theme Palenight High Contrast",
//
"workbench.editor.untitled.hint": "hidden",
//
"window.dialogStyle": "custom",
// macOS Sierra
"window.nativeTabs": true, // this is great, macOS only
// Linux Windows
"window.titleBarStyle": "custom",
//
"workbench.activityBar.visible": true,
//
// 使
//
"workbench.editor.closeOnFileDelete": true,
//
"workbench.editor.highlightModifiedTabs": true,
// antialiased:
"workbench.fontAliasing": "antialiased",
//
"workbench.list.smoothScrolling": true,
//
"workbench.sideBar.location": "left",
// Microsoft
// onlyEnabledExtensions:
"extensions.autoUpdate": "onlyEnabledExtensions",
//
"extensions.ignoreRecommendations": true,
//
"terminal.integrated.cursorBlinking": true,
//
"terminal.integrated.cursorStyle": "underline",
// 1-1000
"terminal.integrated.fontWeight": "300",
// ()
"terminal.integrated.persistentSessionReviveProcess": "never",
//
"terminal.integrated.tabs.enabled": true,
//
"explorer.confirmDelete": false,
//
"explorer.confirmDragAndDrop": false,
//
"explorer.experimental.fileNesting.enabled": true,
//
"explorer.experimental.fileNesting.expand": false,
//
"explorer.experimental.fileNesting.patterns": {
".gitignore": ".gitattributes, .gitmodules, .gitmessage, .mailmap, .git-blame*",
"*.js": "$(capture).js.map, $(capture).min.js, $(capture).d.ts",
"*.jsx": "$(capture).js",
"*.ts": "$(capture).js, $(capture).*.ts",
"*.tsx": "$(capture).ts",
"*.vue": "$(capture).*.ts, $(capture).*.js",
"index.d.ts": "*.d.ts",
"shims.d.ts": "*.d.ts",
"*.cpp": "$(capture).hpp, $(capture).h, $(capture).hxx",
"*.cxx": "$(capture).hpp, $(capture).h, $(capture).hxx",
"*.cc": "$(capture).hpp, $(capture).h, $(capture).hxx",
"*.c": "$(capture).h",
"go.mod": ".air*, go.sum",
"default.nix": "shell.nix",
"flake.nix": "flake.lock",
"BUILD.bazel": "*.bzl, *.bazel, *.bazelrc, bazel.rc, .bazelignore, .bazelproject, WORKSPACE",
"CMakeLists.txt": "*.cmake, *.cmake.in, .cmake-format.yaml, CMakePresets.json",
".clang-tidy": ".clang-format",
".env": "*.env, .env.*, env.d.ts",
"dockerfile": ".dockerignore, dockerfile*",
"package.json": ".browserslist*, .circleci*, .codecov, .commitlint*, .editorconfig, .eslint*, .firebase*, .flowconfig, .github*, .gitlab*, .gitpod*, .huskyrc*, .jslint*, .lintstagedrc*, .markdownlint*, .mocha*, .node-version, .nodemon*, .npm*, .nvmrc, .pm2*, .pnp.*, .pnpm*, .prettier*, .releaserc*, .sentry*, .stackblitz*, .styleci*, .stylelint*, .tazerc*, .textlint*, .tool-versions, .travis*, .vscode*, .watchman*, .xo-config*, .yamllint*, .yarnrc*, api-extractor.json, appveyor*, ava.config.*, azure-pipelines*, bower.json, build.config.*, commitlint*, crowdin*, cypress.json, dangerfile*, dprint.json, firebase.json, grunt*, gulp*, jasmine.*, jenkins*, jest.config.*, jsconfig.*, karma*, lerna*, lint-staged*, nest-cli.*, netlify*, nodemon*, nx.*, package-lock.json, playwright.config.*, pm2.*, pnpm*, prettier*, pullapprove*, puppeteer.config.*, renovate*, rollup.config.*, stylelint*, tsconfig.*, tsdoc.*, tslint*, tsup.config.*, turbo*, typedoc*, vercel*, vetur.config.*, vitest.config.*, webpack.config.*, workspace.json, xo.config.*, yarn*",
"rush.json": ".browserslist*, .circleci*, .codecov, .commitlint*, .editorconfig, .eslint*, .firebase*, .flowconfig, .github*, .gitlab*, .gitpod*, .huskyrc*, .jslint*, .lintstagedrc*, .markdownlint*, .mocha*, .node-version, .nodemon*, .npm*, .nvmrc, .pm2*, .pnp.*, .pnpm*, .prettier*, .releaserc*, .sentry*, .stackblitz*, .styleci*, .stylelint*, .tazerc*, .textlint*, .tool-versions, .travis*, .vscode*, .watchman*, .xo-config*, .yamllint*, .yarnrc*, api-extractor.json, appveyor*, ava.config.*, azure-pipelines*, bower.json, build.config.*, commitlint*, crowdin*, cypress.json, dangerfile*, dprint.json, firebase.json, grunt*, gulp*, jasmine.*, jenkins*, jest.config.*, jsconfig.*, karma*, lerna*, lint-staged*, nest-cli.*, netlify*, nodemon*, nx.*, package-lock.json, playwright.config.*, pm2.*, pnpm*, prettier*, pullapprove*, puppeteer.config.*, renovate*, rollup.config.*, stylelint*, tsconfig.*, tsdoc.*, tslint*, tsup.config.*, turbo*, typedoc*, vercel*, vetur.config.*, vitest.config.*, webpack.config.*, workspace.json, xo.config.*, yarn*",
"readme.*": "authors, backers.md, changelog*, citation*, code_of_conduct.md, codeowners, contributing.md, contributors, copying, credits, governance.md, history.md, license*, maintainers, readme*, security.md, sponsors.md",
"cargo.toml": ".clippy.toml, .rustfmt.toml, cargo.lock, clippy.toml, cross.toml, rust-toolchain.toml, rustfmt.toml",
"gemfile": ".ruby-version, gemfile.lock",
"composer.json": "composer.lock, phpunit.xml*, psalm*.xml",
"vite.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .htmlnanorc*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, cssnano.config.*, cypress.json, env.d.ts, htmlnanorc.*, index.html, jasmine.*, jest.config.*, jsconfig.*, karma*, playwright.config.*, postcss.config.*, puppeteer.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"vue.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .htmlnanorc*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, cssnano.config.*, cypress.json, env.d.ts, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, playwright.config.*, postcss.config.*, puppeteer.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"nuxt.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .htmlnanorc*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, cssnano.config.*, cypress.json, env.d.ts, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, playwright.config.*, postcss.config.*, puppeteer.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"next.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .htmlnanorc*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, cssnano.config.*, cypress.json, env.d.ts, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, next-env.d.ts, playwright.config.*, postcss.config.*, puppeteer.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"svelte.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .htmlnanorc*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, cssnano.config.*, cypress.json, env.d.ts, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, mdsvex.config.js, playwright.config.*, postcss.config.*, puppeteer.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"remix.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .htmlnanorc*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, cssnano.config.*, cypress.json, env.d.ts, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, playwright.config.*, postcss.config.*, puppeteer.config.*, remix.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*"
},
"[typescript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
}
}

View File

@ -1,34 +1,29 @@
## 目前已有脚手架列表
# my_midway_project
| 名称 | 说明 | 技术栈 |
| ------- | --------------------------- | --------------------- |
| nextJs | 基于 React 的服务端渲染方案 | nextJs + axios + antd |
| ReactJs | 基于 React 的业务型脚手架 | umiJs + axios + antd |
| TaroJs | 基于 React 的多端适配方案 | TaroJs 全家桶 |
| Vue | 基于 Vue 的业务型脚手架 | vueJs 全家桶 |
| Gulp | 基于 Gulp 的清凉型脚手架 | -- |
## QuickStart
## 快速上手
<!-- add docs here for user -->
### 1. 安装相关依赖
see [midway docs][midway] for more detail.
```js
// 推荐
yarn global add @nicecode/cli
### Development
// or
// npm install @nicecode/cli -g
```bash
$ npm i
$ npm run dev
$ open http://localhost:7001/
```
### 2. 运行命令
### Deploy
```js
// 查看脚手架版本号,是否安装成功
nice - V
```bash
$ npm start
```
### 3. 创建项目
### npm scripts
```js
nice create ${项目名称}
```
- 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/'],
};

56
package.json Normal file
View File

@ -0,0 +1,56 @@
{
"name": "my-midway-template",
"version": "1.0.0",
"description": "",
"private": true,
"dependencies": {
"@midwayjs/bootstrap": "^3.0.0",
"@midwayjs/core": "^3.0.0",
"@midwayjs/cross-domain": "^3.5.3",
"@midwayjs/decorator": "^3.0.0",
"@midwayjs/info": "^3.0.0",
"@midwayjs/koa": "^3.0.0",
"@midwayjs/logger": "^2.14.0",
"@midwayjs/swagger": "^3.5.3",
"@midwayjs/typegoose": "^3.5.3",
"@midwayjs/validate": "^3.0.0"
},
"devDependencies": {
"@midwayjs/cli": "^1.2.90",
"@midwayjs/mock": "^3.0.0",
"@typegoose/typegoose": "^9.12.1",
"@types/jest": "^26.0.10",
"@types/koa": "^2.13.4",
"@types/node": "14",
"cross-env": "^6.0.0",
"jest": "^26.4.0",
"mongoose": "^6.6.2",
"mwts": "^1.0.5",
"swagger-ui-dist": "^4.14.1",
"ts-jest": "^26.2.0",
"typescript": "~4.6.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": "dev",
"license": "MIT"
}

View File

@ -0,0 +1,27 @@
import { MidwayConfig } from '@midwayjs/core';
export default {
// use for cookie sign key, should change to your own and keep security
keys: '1664331917250_5937',
koa: {
port: 7001,
},
cors: {
credentials: false,
},
// mongoose: {
// dataSource: {
// default: {
// uri: 'mongodb://localhost:27017/test',
// options: {
// useNewUrlParser: true,
// useUnifiedTopology: true,
// user: '***********',
// pass: '***********'
// },
// // 关联实体
// entities: []
// }
// }
// },
} as MidwayConfig;

View File

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

37
src/configuration.ts Normal file
View File

@ -0,0 +1,37 @@
import { Configuration, App } from '@midwayjs/decorator';
import * as koa from '@midwayjs/koa';
import * as validate from '@midwayjs/validate';
import * as info from '@midwayjs/info';
import { join } from 'path';
import * as crossDomain from '@midwayjs/cross-domain';
import * as swagger from '@midwayjs/swagger';
// import * as typegoose from '@midwayjs/typegoose';
// import { DefaultErrorFilter } from './filter/default.filter';
// import { NotFoundFilter } from './filter/notfound.filter';
import { ReportMiddleware } from './middleware/report.middleware';
@Configuration({
imports: [
crossDomain,
koa,
validate,
// typegoose, // mongodb开关
{
component: info,
enabledEnvironment: ['local'],
},
swagger
],
importConfigs: [join(__dirname, './config')],
})
export class ContainerLifeCycle {
@App()
app: koa.Application;
async onReady() {
// add middleware
this.app.useMiddleware([ReportMiddleware]);
// add filter
// this.app.useFilter([NotFoundFilter, DefaultErrorFilter]);
}
}

View File

@ -0,0 +1,36 @@
import { Inject, Controller, Get, Query, Body, Post, Param } from '@midwayjs/decorator';
import { Context } from '@midwayjs/koa';
import { ApiBody, BodyContentType } from '@midwayjs/swagger'
import { UserService } from '../service/user.service';
import { CatIo, CreateCatDto } from '../interface'
@Controller('/api')
export class APIController {
@Inject()
ctx: Context;
@Inject()
userService: UserService;
@Get('/get_user')
@Post('/get_user')
async getUser(
@Query('uid') uid: number,
@Body() createCatDto: CreateCatDto
) {
const user = await this.userService.getUser({ uid });
return { success: true, message: 'OK', data: user };
}
@Post('/upload')
@ApiBody({
description: 'this is body',
contentType: BodyContentType.Multipart
})
async upload(
@Body() createCatDto: CatIo,
@Param('breed') breed: string
) {
return { success: true, message: 'OK', data: 'hh' };
}
}

View File

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

9
src/entity/user.ts Normal file
View File

@ -0,0 +1,9 @@
import { prop } from '@typegoose/typegoose';
export class User {
@prop()
public name?: string;
@prop({ type: () => [String] })
public jobs?: string[];
}

View File

@ -0,0 +1,13 @@
import { Catch } from '@midwayjs/decorator';
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,11 @@
import { Catch } from '@midwayjs/decorator';
import { 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');
}
}

31
src/interface.ts Normal file
View File

@ -0,0 +1,31 @@
/**
* @description User-Service parameters
*/
import { ApiProperty } from "@midwayjs/swagger";
export interface IUserOptions {
uid: number;
}
export class CreateCatDto {
@ApiProperty({ example: 'Kitty', description: '名称'})
name: string;
@ApiProperty({ example: '1', description: '年龄'})
age: number;
@ApiProperty({ example: 'bbbb', description: '职位'})
breed: string;
}
export class CatIo {
@ApiProperty({ example: 'bbbb', description: '职位'})
breed: string;
@ApiProperty({
type: 'string',
format: 'binary',
description: '文件上传'
})
file: any;
}

View File

@ -0,0 +1,28 @@
import { IMiddleware } from '@midwayjs/core';
import { Middleware } from '@midwayjs/decorator';
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/decorator';
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"
]
}