This commit is contained in:
pincman 2024-05-10 06:29:02 +08:00
parent 8cfbfa85cb
commit 894d296159
29 changed files with 497 additions and 782 deletions

View File

@ -12,15 +12,17 @@
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"@3rapp/common": "workspace:*",
"@3rapp/api": "workspace:*",
"@ant-design/cssinjs": "^1.20.0", "@ant-design/cssinjs": "^1.20.0",
"antd": "^5.17.0", "antd": "^5.17.0",
"axios": "^1.6.8",
"deepmerge": "^4.3.1", "deepmerge": "^4.3.1",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0" "react-dom": "^18.2.0"
}, },
"devDependencies": { "devDependencies": {
"@3rapp/code-config": "workspace:*", "@3rapp/code-config": "workspace:*",
"@3rapp/utils": "workspace:*",
"@types/node": "^20.12.10", "@types/node": "^20.12.10",
"@types/react": "^18.2.66", "@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22", "@types/react-dom": "^18.2.22",

View File

@ -1,4 +1,4 @@
import { pathResolve } from '@3rapp/utils'; import { pathResolve } from '@3rapp/common';
import merge from 'deepmerge'; import merge from 'deepmerge';
import { ConfigEnv, UserConfig } from 'vite'; import { ConfigEnv, UserConfig } from 'vite';
@ -19,6 +19,16 @@ export const createConfig = (params: ConfigEnv, configure?: Configure): UserConf
localsConvention: 'camelCaseOnly', localsConvention: 'camelCaseOnly',
}, },
}, },
server: {
proxy: {
'/api': {
target: 'http://localhost:3001/api',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
cors: true,
},
plugins: createPlugins(isBuild), plugins: createPlugins(isBuild),
}, },
typeof configure === 'function' ? configure(params, isBuild) : {}, typeof configure === 'function' ? configure(params, isBuild) : {},

View File

@ -1,15 +1,34 @@
// src/app.tsx // src/app.tsx
import { PostEntity } from '@3rapp/api/modules/content/entities/post.entity';
import { StyleProvider } from '@ant-design/cssinjs'; import { StyleProvider } from '@ant-design/cssinjs';
import { Button, ConfigProvider, theme, App as AntdApp } from 'antd'; import { Button, ConfigProvider, theme, App as AntdApp } from 'antd';
// import 'dayjs/locale/zh-cn'; // import 'dayjs/locale/zh-cn';
import zhCN from 'antd/locale/zh_CN'; import zhCN from 'antd/locale/zh_CN';
import { FC } from 'react'; import axios from 'axios';
import { FC, useEffect, useState } from 'react';
import $styles from './app.module.css'; import $styles from './app.module.css';
const getPosts = async () => {
let data: PostEntity[] = [];
try {
const res = await axios.get('/api/posts');
data = res.data;
} catch (err) {
console.log('Error:', err);
}
return data;
};
const App: FC = () => { const App: FC = () => {
const [data, setData] = useState<PostEntity[]>([]);
useEffect(() => {
(async () => {
setData(await getPosts());
})();
}, []);
return ( return (
<ConfigProvider <ConfigProvider
locale={zhCN} locale={zhCN}
@ -38,6 +57,12 @@ const App: FC = () => {
> >
</Button> </Button>
<h2></h2>
<ul>
{data.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</div> </div>
</div> </div>
</AntdApp> </AntdApp>

4
apps/admin/src/type.ts Normal file
View File

@ -0,0 +1,4 @@
export interface Post {
title: string;
body: string;
}

View File

@ -3,8 +3,6 @@
"collection": "@nestjs/schematics", "collection": "@nestjs/schematics",
"sourceRoot": "src", "sourceRoot": "src",
"compilerOptions": { "compilerOptions": {
"deleteOutDir": true, "deleteOutDir": true
"builder": "swc",
"typeCheck": true
} }
} }

View File

@ -3,8 +3,15 @@
"version": "0.0.1", "version": "0.0.1",
"description": "", "description": "",
"author": "", "author": "",
"private": true,
"license": "UNLICENSED", "license": "UNLICENSED",
"main": "dist/main.js",
"types": "dist/main.d.ts",
"exports": {
".": {
"import": "./dist/main.d.ts"
},
"./*": "./dist/*.d.ts"
},
"scripts": { "scripts": {
"cli": "nest", "cli": "nest",
"db": "mikro-orm", "db": "mikro-orm",
@ -23,15 +30,18 @@
"test:e2e": "jest --config ./test/jest-e2e.json" "test:e2e": "jest --config ./test/jest-e2e.json"
}, },
"dependencies": { "dependencies": {
"@3rapp/common": "workspace:*",
"@mikro-orm/cli": "^6.2.5", "@mikro-orm/cli": "^6.2.5",
"@mikro-orm/core": "^6.2.5", "@mikro-orm/core": "^6.2.5",
"@mikro-orm/migrations": "^6.2.5", "@mikro-orm/migrations": "^6.2.5",
"@mikro-orm/nestjs": "^5.2.3", "@mikro-orm/nestjs": "^5.2.3",
"@mikro-orm/postgresql": "^6.2.5", "@mikro-orm/postgresql": "^6.2.5",
"@mikro-orm/reflection": "^6.2.5",
"@mikro-orm/seeder": "^6.2.5", "@mikro-orm/seeder": "^6.2.5",
"@nestjs/common": "^10.3.8", "@nestjs/common": "^10.3.8",
"@nestjs/core": "^10.3.8", "@nestjs/core": "^10.3.8",
"@nestjs/platform-fastify": "^10.3.8", "@nestjs/platform-fastify": "^10.3.8",
"deepmerge": "^4.3.1",
"fastify": "^4.26.2", "fastify": "^4.26.2",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
@ -41,6 +51,7 @@
"devDependencies": { "devDependencies": {
"@3rapp/code-config": "workspace:*", "@3rapp/code-config": "workspace:*",
"@faker-js/faker": "^8.4.1", "@faker-js/faker": "^8.4.1",
"@mikro-orm/sql-highlighter": "^1.0.1",
"@nestjs/cli": "^10.3.2", "@nestjs/cli": "^10.3.2",
"@nestjs/schematics": "^10.1.1", "@nestjs/schematics": "^10.1.1",
"@nestjs/testing": "^10.3.8", "@nestjs/testing": "^10.3.8",

View File

@ -1,20 +1,14 @@
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { AppController } from './app.controller'; import { AppController } from './app.controller';
import { AppService } from './app.service'; import { AppService } from './app.service';
import { database } from './config/database.config'; import { database } from './config/database.config';
import { moduleImports } from './module.list'; import { ContentModule } from './modules/content/content.module';
import { DatabaseModule } from './modules/database/database.module';
import { UserModule } from './modules/user/user.module';
@Module({ @Module({
imports: [ imports: [DatabaseModule.forRoot(database()), UserModule, ContentModule],
MikroOrmModule.forRoot({
...database(),
// registerRequestContext: true,
// autoLoadEntities: true,
}),
...moduleImports,
],
controllers: [AppController], controllers: [AppController],
providers: [AppService], providers: [AppService],
}) })

View File

@ -1,27 +1,16 @@
import { Migrator } from '@mikro-orm/migrations'; import { defineConfig } from '@mikro-orm/postgresql';
import { defineConfig, Utils } from '@mikro-orm/postgresql';
import { SeedManager } from '@mikro-orm/seeder'; import { PostgreSqlOptions } from '@mikro-orm/postgresql/PostgreSqlMikroORM';
import { moduleImports } from '@/module.list'; import { getBbOptions } from '@/modules/database/helpers';
import { getEntities } from '@/modules/database/helpers';
export const database = () => export const database = () =>
defineConfig({ defineConfig(
host: '127.0.0.1', getBbOptions<PostgreSqlOptions>({
user: 'postgres', host: '127.0.0.1',
password: '123456', user: 'postgres',
dbName: '3rapp', password: '123456',
entities: getEntities(moduleImports), dbName: '3rapp',
extensions: [Migrator, SeedManager], }),
migrations: { );
disableForeignKeys: false,
tableName: 'migrations',
path: Utils.detectTsNode() ? 'src/database/migrations' : 'dist/database/migrations',
},
seeder: {
path: Utils.detectTsNode() ? 'src/database/seeders' : 'dist/database/seeders',
defaultSeeder: 'DatabaseSeeder',
},
});
export default database(); export default database();

View File

@ -14,6 +14,8 @@ async function bootstrap() {
}); });
// 设置全局访问前缀 // 设置全局访问前缀
app.setGlobalPrefix('api'); app.setGlobalPrefix('api');
// 关闭nestjs进程自动关闭mikroorm等进程
app.enableShutdownHooks();
// 启动后的输出 // 启动后的输出
await app.listen(3001, () => { await app.listen(3001, () => {
console.log(); console.log();

View File

@ -1,6 +0,0 @@
import { ModuleMetadata } from '@nestjs/common';
import { ContentModule } from './modules/content/content.module';
import { UserModule } from './modules/user/user.module';
export const moduleImports: ModuleMetadata['imports'] = [UserModule, ContentModule];

View File

@ -1,11 +1,14 @@
import { AnyEntity, EntityName } from '@mikro-orm/core'; import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { PostController } from './controllers/post.controller';
import { PostEntity } from './entities/post.entity'; import { PostEntity } from './entities/post.entity';
import { PostService } from './services/post.service';
@Module({}) @Module({
export class ContentModule { imports: [MikroOrmModule.forFeature({ entities: [PostEntity] })],
static entities(): EntityName<AnyEntity>[] { controllers: [PostController],
return [PostEntity]; providers: [PostService],
} exports: [PostService],
} })
export class ContentModule {}

View File

@ -0,0 +1,13 @@
import { Controller, Get } from '@nestjs/common';
import { PostService } from '../services/post.service';
@Controller('posts')
export class PostController {
constructor(private postService: PostService) {}
@Get()
async list() {
return this.postService.list();
}
}

View File

@ -11,10 +11,10 @@ export class PostEntity {
id = v4(); id = v4();
@Property({ index: true }) @Property({ index: true })
title: string; title!: string;
@Property({ type: 'text', lazy: true }) @Property({ type: 'text', lazy: true })
body: string; body!: string;
@Property({ type: ArrayType, nullable: true }) @Property({ type: ArrayType, nullable: true })
keywords?: string[]; keywords?: string[];

View File

@ -4,9 +4,8 @@ import { PostRepository } from '../repositories/post.repository';
@Injectable() @Injectable()
export class PostService { export class PostService {
constructor(protected postRepo: PostRepository) {} constructor(private readonly postRepo: PostRepository) {}
// @CreateRequestContext<PostService>((t) => t.postRepo)
async list() { async list() {
return this.postRepo.findAll(); return this.postRepo.findAll();
} }

View File

@ -0,0 +1,28 @@
import { MikroORM } from '@mikro-orm/core';
import { MikroOrmModule, MikroOrmModuleSyncOptions } from '@mikro-orm/nestjs';
// import { SqlHighlighter } from '@mikro-orm/sql-highlighter';
import { DynamicModule, Module, OnModuleInit } from '@nestjs/common';
import { getBbOptions } from './helpers';
@Module({})
export class DatabaseModule implements OnModuleInit {
constructor(private readonly orm: MikroORM) {}
async onModuleInit(): Promise<void> {
await this.orm.getMigrator().up();
}
static forRoot(options: MikroOrmModuleSyncOptions = {}): DynamicModule {
return {
global: true,
module: DatabaseModule,
imports: [
MikroOrmModule.forRootAsync({
useFactory: () => getBbOptions<MikroOrmModuleSyncOptions>(options),
}),
],
exports: [MikroOrmModule],
};
}
}

View File

@ -1,11 +1,35 @@
import { deepMerge } from '@3rapp/common';
import { base, zh_CN, en, Faker } from '@faker-js/faker'; import { base, zh_CN, en, Faker } from '@faker-js/faker';
import { ModuleMetadata } from '@nestjs/common'; import { Utils } from '@mikro-orm/core';
import { isFunction } from 'lodash'; import { Migrator } from '@mikro-orm/migrations';
export const getEntities = (modules: ModuleMetadata['imports'] = []) => import { MikroOrmModuleSyncOptions } from '@mikro-orm/nestjs';
modules import { SeedManager } from '@mikro-orm/seeder';
.map((m) => ('entities' in m && isFunction(m.entities) ? m.entities() : []))
.reduce((o, n) => [...o, ...n], []); export const getBbOptions = <T>(options: MikroOrmModuleSyncOptions) =>
deepMerge(
{
// registerRequestContext: false,
extensions: [Migrator, SeedManager],
migrations: {
disableForeignKeys: false,
tableName: 'migrations',
path: Utils.detectTsNode() ? 'src/database/migrations' : 'dist/database/migrations',
},
seeder: {
path: Utils.detectTsNode() ? 'src/database/seeders' : 'dist/database/seeders',
defaultSeeder: 'DatabaseSeeder',
},
entities: ['dist/**/*.entity.js', 'node_modules/@3rapp/**/*.entity.js'],
entitiesTs: ['src/**/*.entity.ts', 'node_modules/@3rapp/**/*.entity.ts'],
// highlighter: new SqlHighlighter(),
// metadataProvider: TsMorphMetadataProvider,
debug: true,
} as MikroOrmModuleSyncOptions,
options,
'replace',
) as T;
const faker = new Faker({ const faker = new Faker({
locale: [zh_CN, en, base], locale: [zh_CN, en, base],

View File

@ -1,5 +1,5 @@
{ {
"name": "@3rapp/utils", "name": "@3rapp/common",
"version": "0.0.0", "version": "0.0.0",
"files": [ "files": [
"dist" "dist"

View File

@ -0,0 +1 @@
export * from './utils/tools';

View File

@ -1 +0,0 @@
export * from './tools';

File diff suppressed because it is too large Load Diff

View File

@ -15,6 +15,7 @@
"dependsOn": ["^lint"] "dependsOn": ["^lint"]
}, },
"dev": { "dev": {
"dependsOn": ["^dev"],
"cache": false, "cache": false,
"persistent": true "persistent": true
}, },
@ -22,7 +23,7 @@
"dependsOn": ["^build"] "dependsOn": ["^build"]
}, },
"@3rapp/admin#dev": { "@3rapp/admin#dev": {
"dependsOn": ["@3rapp/utils#build"] "dependsOn": ["@3rapp/common#build"]
}, },
"@3rapp/api#db": { "@3rapp/api#db": {
"cache": false, "cache": false,