This commit is contained in:
COOL 2025-01-09 20:40:58 +08:00
parent a5d2305c71
commit dc8d4ecece
26 changed files with 6901 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
}
}

13
.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
logs/
npm-debug.log
yarn-error.log
node_modules/
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')
}

23
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,23 @@
{
"version": "0.2.0",
"configurations": [{
"name": "Cool Admin",
"type": "node",
"request": "launch",
"cwd": "${workspaceRoot}",
"runtimeExecutable": "npm",
"windows": {
"runtimeExecutable": "npm.cmd"
},
"runtimeArgs": [
"run",
"dev"
],
"env": {
"NODE_ENV": "local"
},
"console": "integratedTerminal",
"restart": true,
"autoAttachChildProcesses": true
}]
}

33
LICENSE Normal file
View File

@ -0,0 +1,33 @@
MIT License
Copyright (c) [2025] [厦门闪酷科技开发有限公司]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
MIT 许可证
版权所有 (c) [2025] [厦门闪酷科技开发有限公司]
特此免费授予获得本软件及相关文档文件(“软件”)副本的任何人无限制地处理本软件的权限,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或销售软件的副本,并允许软件提供给其的人员这样做,但须符合以下条件:
上述版权声明和本许可声明应包含在软件的所有副本或主要部分中。
本软件按“原样”提供,不提供任何明示或暗示的担保,包括但不限于对适销性、特定用途适用性和非侵权的担保。在任何情况下,作者或版权持有人均不对因软件或软件使用或其他交易而产生的任何索赔、损害或其他责任负责,无论是在合同诉讼、侵权诉讼或其他诉讼中。

191
README.md Normal file
View File

@ -0,0 +1,191 @@
<p align="center">
<a href="https://midwayjs.org/" target="blank"><img src="https://cool-show.oss-cn-shanghai.aliyuncs.com/admin/logo.png" width="200" alt="Midway Logo" /></a>
</p>
<p align="center">cool-admin(midway版)一个很酷的后台权限管理系统开源免费模块化、插件化、极速开发CRUD方便快速构建迭代后台管理系统支持serverless、docker、普通服务器等多种方式部署
<a href="https://cool-js.com" target="_blank">官网</a> 进一步了解。
<p align="center">
<a href="https://github.com/cool-team-official/cool-admin-midway/blob/master/LICENSE" target="_blank"><img src="https://img.shields.io/badge/license-MIT-green?style=flat-square" alt="GitHub license" />
<a href=""><img src="https://img.shields.io/github/package-json/v/cool-team-official/cool-admin-midway?style=flat-square" alt="GitHub tag"></a>
<img src="https://img.shields.io/github/last-commit/cool-team-official/cool-admin-midway?style=flat-square" alt="GitHub tag"></a>
</p>
## 特性
Ai时代很多老旧的框架已经无法满足现代化的开发需求Cool-Admin开发了一系列的功能让开发变得更简单、更快速、更高效。
- **Ai编码**通过微调大模型学习框架特有写法实现简单功能从Api接口到前端页面的一键生成
- **流程编排**:通过拖拽编排方式,即可实现类似像智能客服这样的功能
- **模块化**:代码是模块化的,清晰明了,方便维护
- **插件化**:插件化的设计,可以通过安装插件的方式扩展如:支付、短信、邮件等功能
![](https://cool-show.oss-cn-shanghai.aliyuncs.com/admin/flow.png)
## 技术栈
- 后端:**`node.js` `midway.js` `koa.js` `typescript`**
- 前端:**`vue.js` `element-plus` `jsx` `pinia` `vue-router`**
- 数据库:**`mysql` `postgresql` `sqlite`**
如果你是前端,后端的这些技术选型对你是特别友好的,前端开发者可以较快速地上手。
如果你是后端Typescript 的语法又跟 java、php 等特别类似,一切看起来也是那么得熟悉。
如果你想使用 java 版本后端,请移步[cool-admin-java](https://cool-js.com/admin/java/introduce.html)
#### 官网
[https://cool-js.com](https://cool-js.com)
## 视频教程
[官方 B 站视频教程](https://www.bilibili.com/video/BV1j1421R7aB)
<!-- 在此次添加使用文档 -->
## 演示
[AI 极速编码](https://cool-js.com/ai/introduce.html)
[https://show.cool-admin.com](https://show.cool-admin.com)
- 账户admin
- 密码123456
<img src="https://cool-show.oss-cn-shanghai.aliyuncs.com/admin/home-mini.png" alt="Admin Home"></a>
#### 项目前端
[https://github.com/cool-team-official/cool-admin-vue](https://github.com/cool-team-official/cool-admin-vue)
[https://gitee.com/cool-team-official/cool-admin-vue](https://gitee.com/cool-team-official/cool-admin-vue)
[https://gitcode.com/cool_team/cool-admin-vue](https://gitcode.com/cool_team/cool-admin-vue)
## 微信群
<img width="260" src="https://cool-show.oss-cn-shanghai.aliyuncs.com/admin/wechat.jpeg?v=1" alt="Admin Wechat"></a>
## 运行
#### 修改数据库配置,配置文件位于`src/config/config.local.ts`
以 Mysql 为例,其他数据库请参考[数据库配置文档](https://cool-js.com/admin/node/quick.html#%E6%95%B0%E6%8D%AE%E5%BA%93%E9%85%8D%E7%BD%AE)
Mysql(`>=5.7版本`),建议 8.0node 版本(`>=16.x`),建议 18.x首次启动会自动初始化并导入数据
```ts
// mysql驱动已经内置无需安装
typeorm: {
dataSource: {
default: {
type: 'mysql',
host: '127.0.0.1',
port: 3306,
username: 'root',
password: '123456',
database: 'cool',
// 自动建表 注意:线上部署的时候不要使用,有可能导致数据丢失
synchronize: true,
// 打印日志
logging: false,
// 字符集
charset: 'utf8mb4',
// 是否开启缓存
cache: true,
// 实体路径
entities: ['**/modules/*/entity'],
},
},
},
```
#### 安装依赖并运行
```bash
$ npm i
$ npm run dev
$ open http://localhost:8001/
```
注: `npm i`如果安装失败可以尝试使用[cnpm](https://developer.aliyun.com/mirror/NPM?from=tnpm),或者切换您的镜像源,推荐使用[pnpm](https://pnpm.io/)
## CURD(快速增删改查)
大部分的后台管理系统,或者 API 服务都是对数据进行管理,所以可以看到大量的 CRUD 场景(增删改查)cool-admin 对此进行了大量地封装,让这块的编码量变得极其地少。
#### 新建一个数据表
`src/modules/demo/entity/goods.ts`,项目启动数据库会自动创建该表,无需手动创建
```ts
import { BaseEntity } from '@cool-midway/core';
import { Column, Entity, Index } from 'typeorm';
/**
* 商品
*/
@Entity('demo_app_goods')
export class DemoAppGoodsEntity extends BaseEntity {
@Column({ comment: '标题' })
title: string;
@Column({ comment: '图片' })
pic: string;
@Column({ comment: '价格', type: 'decimal', precision: 5, scale: 2 })
price: number;
}
```
#### 编写 api 接口
`src/modules/demo/controller/app/goods.ts`,快速编写 6 个 api 接口
```ts
import { CoolController, BaseController } from '@cool-midway/core';
import { DemoAppGoodsEntity } from '../../entity/goods';
/**
* 商品
*/
@CoolController({
api: ['add', 'delete', 'update', 'info', 'list', 'page'],
entity: DemoAppGoodsEntity,
})
export class DemoAppGoodsController extends BaseController {
/**
* 其他接口
*/
@Get('/other')
async other() {
return this.ok('hello, cool-admin!!!');
}
}
```
这样我们就完成了 6 个接口的编写,对应的接口如下:
- `POST /app/demo/goods/add` 新增
- `POST /app/demo/goods/delete` 删除
- `POST /app/demo/goods/update` 更新
- `GET /app/demo/goods/info` 单个信息
- `POST /app/demo/goods/list` 列表信息
- `POST /app/demo/goods/page` 分页查询(包含模糊查询、字段全匹配等)
### 部署
[部署教程](https://cool-js.com/admin/deploy.html)
### 内置指令
- 使用 `npm run lint` 来做代码风格检查。
[midway]: https://midwayjs.org
### 低价服务器
[阿里云、腾讯云、华为云低价云服务器,不限新老](https://cool-js.com/service/cloud)

10
bootstrap.js vendored Normal file
View File

@ -0,0 +1,10 @@
const { Bootstrap } = require('@midwayjs/bootstrap');
// 显式以组件方式引入用户代码
Bootstrap.configure({
// 这里引用的是编译后的入口,本地开发不走这个文件
// eslint-disable-next-line node/no-unpublished-require
imports: require('./dist/index'),
// 禁用依赖注入的目录扫描
moduleDetector: false,
}).run();

2
build/pkg.log Normal file
View File

@ -0,0 +1,2 @@
> pkg@5.8.1
> Fetching base Node.js binaries to PKG_CACHE_PATH

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/'],
};

60
package.json Normal file
View File

@ -0,0 +1,60 @@
{
"name": "cool-admin-midway",
"version": "8.0.0",
"description": "一个很酷的Ai开发快速框架",
"private": true,
"dependencies": {
"@cool-midway/core": "file:/Users/ap/Documents/src/admin/midway-packages/core",
"@midwayjs/bootstrap": "^3.19.3",
"@midwayjs/core": "^3.19.0",
"@midwayjs/info": "^3.19.2",
"@midwayjs/koa": "^3.19.2",
"@midwayjs/logger": "^3.4.2",
"@midwayjs/validate": "^3.19.2"
},
"devDependencies": {
"@midwayjs/bundle-helper": "^1.3.0",
"@midwayjs/mock": "^3.19.2",
"@types/jest": "^29.5.14",
"@types/node": "22",
"@vercel/ncc": "^0.38.3",
"cross-env": "^7.0.3",
"jest": "^29.7.0",
"mwts": "^1.3.0",
"mwtsc": "^1.15.1",
"pkg": "^5.8.1",
"ts-jest": "^29.2.5",
"typescript": "~5.7.3"
},
"engines": {
"node": ">=18.0.0"
},
"scripts": {
"start": "NODE_ENV=production node ./bootstrap.js",
"dev": "cool check && cross-env NODE_ENV=local mwtsc --watch --run @midwayjs/mock/app.js",
"test": "cross-env NODE_ENV=unittest jest",
"cov": "jest --coverage",
"lint": "mwts check",
"lint:fix": "mwts fix",
"ci": "npm run cov",
"build": "mwtsc --cleanOutDir",
"bundle": "bundle && npm run build && ncc build bootstrap.js -o build",
"bundle_start": "NODE_ENV=production node ./build/index.js",
"pkg": "pkg . -d > build/pkg.log"
},
"bin": "./bootstrap.js",
"pkg": {
"scripts": "dist/**/*.js",
"assets": [],
"targets": [
"node18-macos-x64"
],
"outputPath": "build"
},
"repository": {
"type": "git",
"url": "https://cool-js.com"
},
"author": "COOL",
"license": "MIT"
}

6315
pnpm-lock.yaml generated 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: '1736423310302_5051',
koa: {
port: 7001,
},
} as MidwayConfig;

View File

@ -0,0 +1,3 @@
import { MidwayConfig } from '@midwayjs/core';
export default {} as MidwayConfig;

38
src/configuration.ts Normal file
View File

@ -0,0 +1,38 @@
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 { ReportMiddleware } from './middleware/report.middleware';
import * as DefaultConfig from './config/config.default';
import * as LocalConfig from './config/config.local';
import * as cool from '@cool-midway/core';
@Configuration({
imports: [
koa,
validate,
// cool-admin 官方组件 https://cool-js.com
cool,
{
component: info,
enabledEnvironment: ['local'],
},
],
importConfigs: [
{
default: DefaultConfig,
local: LocalConfig,
},
],
})
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');
}
}

11
src/index.ts Normal file
View File

@ -0,0 +1,11 @@
/** This file generated by @midwayjs/bundle-helper */
export { MainConfiguration as Configuration } from './configuration';
export * from './config/config.default';
export * from './config/config.local';
export * from './middleware/report.middleware';
export * from './interface';
export * from './service/user.service';
export * from './controller/api.controller';
export * from './controller/home.controller';
export * from './filter/default.filter';
export * from './filter/notfound.filter';

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);
});
});

28
tsconfig.json Normal file
View File

@ -0,0 +1,28 @@
{
"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",
"rootDir": "src"
},
"exclude": [
"*.js",
"*.ts",
"dist",
"node_modules",
"test"
]
}