feat: 修改为bun,优化代码

This commit is contained in:
2025-05-20 00:36:32 +08:00
parent 3de5754f24
commit 1f4404fa5c
32 changed files with 618 additions and 1035 deletions

View File

@@ -2,10 +2,11 @@ import path from 'path';
import dotenv from 'dotenv';
// import { useConfig } from '@kevisual/use-config/env';
const envFiles = [
export const envFiles = [
path.resolve(process.cwd(), process.env.NODE_ENV === 'development' ? '.env.dev' : '.env'),
// path.resolve(process.cwd(), '.env'), //
];
console.log('envFiles', envFiles);
export const config = dotenv.config({
path: envFiles,
override: true,

View File

@@ -1,18 +1,29 @@
import { Redis } from 'ioredis';
import { config } from './config.ts';
const redisConfig = {
host: config.REDIS_HOST || 'localhost',
port: parseInt(config.REDIS_PORT || '6379'),
password: config.REDIS_PASSWORD,
};
export const createRedisClient = (options = {}) => {
const redisClient = new Redis({
host: 'localhost', // Redis 服务器的主机名或 IP 地址
port: 6379, // Redis 服务器的端口号
// password: 'your_password', // Redis 的密码 (如果有)
db: 0, // 要使用的 Redis 数据库索引 (0-15)
keyPrefix: '', // key 前缀
retryStrategy(times) {
// 连接重试策略
return Math.min(times * 50, 2000); // 每次重试时延迟增加
},
maxRetriesPerRequest: null, // 允许请求重试的次数 (如果需要无限次重试)
...redisConfig,
...options,
});
return redisClient;
};
// 配置 Redis 连接
export const redis = new Redis({
host: 'localhost', // Redis 服务器的主机名或 IP 地址
port: 6379, // Redis 服务器的端口号
// password: 'your_password', // Redis 的密码 (如果有)
db: 0, // 要使用的 Redis 数据库索引 (0-15)
keyPrefix: '', // key 前缀
retryStrategy(times) {
// 连接重试策略
return Math.min(times * 50, 2000); // 每次重试时延迟增加
},
maxRetriesPerRequest: null, // 允许请求重试的次数 (如果需要无限次重试)
});
export const redis = createRedisClient();
// 监听连接事件
redis.on('connect', () => {
@@ -24,5 +35,5 @@ redis.on('error', (err) => {
});
// 初始化 Redis 客户端
export const redisPublisher = new Redis(); // 用于发布消息
export const redisSubscriber = new Redis(); // 用于订阅消息
export const redisPublisher = createRedisClient(); // 用于发布消息
export const redisSubscriber = createRedisClient(); // 用于订阅消息

View File

@@ -11,7 +11,8 @@ export type PostgresConfig = {
};
};
if (!config.POSTGRES_PASSWORD || !config.POSTGRES_USER) {
console.error('postgres config is required password and user');
log.error('postgres config is required password and user');
log.error('config', config);
process.exit(1);
}
const postgresConfig = {

16
src/program.ts Normal file
View File

@@ -0,0 +1,16 @@
import { program, Command } from 'commander';
// import { useContextKey } from '@kevisual/use-config/context';
// import * as redisLib from './modules/redis.ts';
// import * as sequelizeLib from './modules/sequelize.ts';
// import * as minioLib from './modules/minio.ts';
// export const redis = useContextKey('redis', () => redisLib.redis);
// export const redisPublisher = useContextKey('redisPublisher', () => redisLib.redisPublisher);
// export const redisSubscriber = useContextKey('redisSubscriber', () => redisLib.redisSubscriber);
// export const minioClient = useContextKey('minioClient', () => minioLib.minioClient);
// export const sequelize = useContextKey('sequelize', () => sequelizeLib.sequelize);
export { program, Command };
program.description('code-center的一部分工具');
program.version('1.0.0', '-v, --version');

View File

@@ -16,7 +16,7 @@ export { manager };
// console.log('app', app, );
// console.log('app2 context', global.context);
// console.log('app equal', app === ManagerApp);
loadManager();
loadManager({ runtime: 'server' });
// middleware: ['auth-admin']
/*
@@ -31,4 +31,4 @@ loadManager();
path: 'local-apps',
key: 'delete',
*/
*/

View File

@@ -3,8 +3,8 @@ import { PageModel } from '../models/index.ts';
import { ContainerModel } from '@/routes/container/models/index.ts';
import { Op } from 'sequelize';
import { getContainerData } from './get-container.ts';
import path from 'path';
import fs from 'fs';
import path from 'node:path';
import fs from 'node:fs';
import { getHTML, getDataJs, getOneHTML } from './file-template.ts';
import { minioClient } from '@/app.ts';
import { bucketName } from '@/modules/minio.ts';
@@ -174,7 +174,7 @@ export const getZip = async (page: PageModel, opts: { tokenUser: any }) => {
// 添加 JavaScript 字符串作为文件到 zip 中
zip.append(dataJs, { name: 'data.js' });
zip.append(JSON.stringify(page), { name: 'app.config.json5' });
zip.append(JSON.stringify(page), { name: 'app.config.json' });
// 可以继续添加更多内容,文件或目录等
// zip.append('Another content', { name: 'other.txt' });

9
src/run.ts Normal file
View File

@@ -0,0 +1,9 @@
import { program } from './program.ts';
//
import './scripts/change-user-pwd.ts';
import './scripts/list-app.ts';
//
program.parse(process.argv);

View File

@@ -0,0 +1,50 @@
import { program, Command } from '../program.ts';
import { initUser, logger, close } from './common.ts';
const usrCommand = new Command('user').description('用户相关操作');
program.addCommand(usrCommand);
const changePwd = new Command('pwd')
.description('修改用户密码')
.option('-u, --username <username>', '用户名')
.option('-p, --password <password>', '新密码')
.action(async (opts) => {
const username = opts.username;
const password = opts.password;
if (!username) {
logger.error('用户名不能为空');
close();
return;
}
const { User } = await initUser();
const newPassword = password || 'kevisual';
logger.info(`用户名: ${username}`);
logger.info(`新密码: ${newPassword}`);
const user = await User.findOne({ where: { username: username }, logging: false });
if (!user) {
logger.error('用户不存在');
return;
}
const newP = await user.createPassword(newPassword);
logger.info('新密码加密成功', '新密码: ', newPassword);
close();
});
usrCommand.addCommand(changePwd);
const list = new Command('list').description('列出所有用户').action(async () => {
console.log('列出所有用户 start');
const { User } = await initUser();
console.log('列出所有用户');
const users = await User.findAll({ limit: 10, order: [['createdAt', 'DESC']] });
if (users.length === 0) {
logger.info('没有用户');
return;
}
users.forEach((user) => {
console.log(`用户名: ${user.username}`);
});
console.log(`用户数量: ${users.length}`);
await close();
});
usrCommand.addCommand(list);

29
src/scripts/common.ts Normal file
View File

@@ -0,0 +1,29 @@
import { config } from '../modules/config.ts';
import { sequelize } from '../modules/sequelize.ts';
export { program, Command } from '../program.ts';
import { User, UserInit, OrgInit, Org } from '@kevisual/code-center-module/models';
import { Logger } from '@kevisual/logger';
export const close = async () => {
process.exit(0);
};
export { sequelize };
export const logger = new Logger({
level: (config?.LOG_LEVEL || 'info') as any,
showTime: true,
});
export const initUser = async () => {
console.log('init user');
await UserInit(sequelize, undefined, {
alter: true,
logging: false,
});
await OrgInit(sequelize, undefined, {
alter: true,
logging: false,
});
return {
User: User,
Org: Org,
};
};

12
src/scripts/list-app.ts Normal file
View File

@@ -0,0 +1,12 @@
import { AppListModel, AppModel } from '../routes/app-manager/module/index.ts';
import { program, Command, close } from './common.ts';
const app = program.command('app');
const appList = new Command('list').action(async () => {
const list = await AppListModel.findAll();
console.log(list.map((item) => item.toJSON()));
close();
});
app.addCommand(appList);

View File

@@ -26,7 +26,7 @@ export const main = async () => {
}
};
// main();
main();
export const changeRootPassword = async () => {
await OrgInit(sequelize, null, {
alter: true,
@@ -38,11 +38,11 @@ export const changeRootPassword = async () => {
});
const user = await User.findOne({ where: { username: 'root' } });
if (user) {
await user.createPassword('Abear123456x');
await user.createPassword('');
await user.save();
console.log('change root password done');
process.exit(0);
}
};
changeRootPassword();
// changeRootPassword();