Initial commit

This commit is contained in:
kevisual
2025-04-16 18:09:31 +08:00
commit bd789de7b6
20 changed files with 6702 additions and 0 deletions

8
src/app.ts Normal file
View File

@@ -0,0 +1,8 @@
import { App } from '@kevisual/router';
import { useContextKey } from '@kevisual/use-config/context';
const init = () => {
return new App();
};
export const app = useContextKey('app', init);

48
src/dev.ts Normal file
View File

@@ -0,0 +1,48 @@
import { app } from './index.ts';
import { useConfig } from '@kevisual/use-config/env';
app
.route({
path: 'auth',
id: 'auth',
})
.define(async (ctx) => {
ctx.query.token = '123';
ctx.state.tokenUser = {
id: '123',
username: 'admin',
};
})
.addTo(app);
app
.route({
path: 'auth-admin',
id: 'auth-admin',
})
.define(async (ctx) => {
ctx.body = '123';
ctx.state.tokenUser = {
id: '123',
username: 'admin',
};
})
.addTo(app);
app
.route({
path: 'demo',
key: 'demo',
})
.define(async (ctx) => {
ctx.body = '123';
})
.addTo(app);
const config = useConfig();
const port = config.PORT || 4000;
console.log('run demo: http://localhost:' + port + '/api/router?path=demo&key=demo');
app.listen(port, () => {
console.log(`server is running at http://localhost:${port}`);
});

3
src/index.ts Normal file
View File

@@ -0,0 +1,3 @@
import { app } from './app.ts';
export { app };

37
src/logger/index.ts Normal file
View File

@@ -0,0 +1,37 @@
import { pino } from 'pino';
import { useConfig } from '@kevisual/use-config/env';
const config = useConfig();
export const logger = pino({
level: config.LOG_LEVEL || 'info',
transport: {
target: 'pino-pretty',
options: {
colorize: true,
translateTime: 'SYS:standard',
ignore: 'pid,hostname',
},
},
serializers: {
error: pino.stdSerializers.err,
req: pino.stdSerializers.req,
res: pino.stdSerializers.res,
},
base: {
app: 'ai-chat',
env: process.env.NODE_ENV || 'development',
},
});
export const logError = (message: string, data?: any) => logger.error({ data }, message);
export const logWarning = (message: string, data?: any) => logger.warn({ data }, message);
export const logInfo = (message: string, data?: any) => logger.info({ data }, message);
export const logDebug = (message: string, data?: any) => logger.debug({ data }, message);
export const log = {
error: logError,
warn: logWarning,
info: logInfo,
debug: logDebug,
};

9
src/main.ts Normal file
View File

@@ -0,0 +1,9 @@
// 单应用实例启动
import { useConfig } from '@kevisual/use-config/env';
import { app } from './index.ts';
const config = useConfig();
const port = config.PORT || 4000;
app.listen(port, () => {
console.log(`server is running at http://localhost:${port}`);
});

28
src/modules/redis.ts Normal file
View File

@@ -0,0 +1,28 @@
import { Redis } from 'ioredis';
// 配置 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, // 允许请求重试的次数 (如果需要无限次重试)
});
// 监听连接事件
redis.on('connect', () => {
console.log('Redis 连接成功');
});
redis.on('error', (err) => {
console.error('Redis 连接错误', err);
});
// 初始化 Redis 客户端
export const redisPublisher = new Redis(); // 用于发布消息
export const redisSubscriber = new Redis(); // 用于订阅消息

31
src/modules/sequelize.ts Normal file
View File

@@ -0,0 +1,31 @@
import { Sequelize } from 'sequelize';
import { useConfig } from '@kevisual/use-config/env';
const config = useConfig();
export type PostgresConfig = {
postgres: {
username: string;
password: string;
host: string;
port: number;
database: string;
};
};
if (!config.POSTGRES_PASSWORD || !config.POSTGRES_USER) {
console.error('postgres config is required password and user');
process.exit(1);
}
const postgresConfig = {
username: config.POSTGRES_USER,
password: config.POSTGRES_PASSWORD,
host: config.POSTGRES_HOST || 'localhost',
port: parseInt(config.POSTGRES_PORT || '5432'),
database: config.POSTGRES_DB || 'postgres',
};
// connect to db
export const sequelize = new Sequelize({
dialect: 'postgres',
...postgresConfig,
// logging: false,
});

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

@@ -0,0 +1,9 @@
import { sequelize, User, UserInit, Org, OrgInit } from '@kevisual/code-center-module';
export { sequelize, User, UserInit, Org, OrgInit };
export const init = () => {
UserInit();
OrgInit();
};
init();

View File

@@ -0,0 +1,119 @@
import { Op } from 'sequelize';
import { AppDemoModel } from './models/index.ts';
import { app } from '@/app.ts';
app
.route({
path: 'app-demo',
key: 'list',
middleware: ['auth'],
})
.define(async (ctx) => {
const tokenUser = ctx.state.tokenUser;
const { page = 1, pageSize = 20, search, sort = 'DESC' } = ctx.query;
const searchWhere = search
? {
[Op.or]: [{ title: { [Op.like]: `%${search}%` } }, { summary: { [Op.like]: `%${search}%` } }],
}
: {};
const { rows: appDemo, count } = await AppDemoModel.findAndCountAll({
where: {
uid: tokenUser.uid,
...searchWhere,
},
offset: (page - 1) * pageSize,
limit: pageSize,
order: [['updatedAt', sort]],
});
ctx.body = {
list: appDemo,
pagination: {
page,
current: page,
pageSize,
total: count,
},
};
})
.addTo(app);
app
.route({
path: 'app-demo',
key: 'update',
middleware: ['auth'],
})
.define(async (ctx) => {
const tokenUser = ctx.state.tokenUser;
const { id, data, updatedAt: _clear, createdAt: _clear2, ...rest } = ctx.query.data;
let appDemo: AppDemoModel;
let isNew = false;
if (id) {
const appDemo = await AppDemoModel.findByPk(id);
if (appDemo.uid !== tokenUser.uid) {
ctx.throw(403, 'No permission');
}
} else {
appDemo = await AppDemoModel.create({
data: data,
...rest,
uid: tokenUser.uid,
});
isNew = true;
}
if (!appDemo) {
ctx.throw(404, 'AppDemo not found');
}
if (!isNew) {
appDemo = await appDemo.update({
data: { ...appDemo.data, ...data },
...rest,
});
}
ctx.body = appDemo;
})
.addTo(app);
app
.route({
path: 'app-demo',
key: 'delete',
middleware: ['auth'],
})
.define(async (ctx) => {
const tokenUser = ctx.state.tokenUser;
const { id, force = false } = ctx.query.data || {};
if (!id) {
ctx.throw(400, 'id is required');
}
const appDemo = await AppDemoModel.findByPk(id);
if (appDemo.uid !== tokenUser.uid) {
ctx.throw(403, 'No permission');
}
await appDemo.destroy({ force });
ctx.body = appDemo;
})
.addTo(app);
app
.route({
path: 'app-demo',
key: 'get',
middleware: ['auth'],
})
.define(async (ctx) => {
const tokenUser = ctx.state.tokenUser;
const { id } = ctx.query.data || {};
if (!id) {
ctx.throw(400, 'id is required');
}
const appDemo = await AppDemoModel.findByPk(id);
if (appDemo.uid !== tokenUser.uid) {
ctx.throw(403, 'No permission');
}
ctx.body = appDemo;
})
.addTo(app);

View File

@@ -0,0 +1,71 @@
import { sequelize } from '@/modules/sequelize.ts';
import { DataTypes, Model } from 'sequelize';
export interface AppDemoData {
[key: string]: any;
}
export type AppDemo = Partial<InstanceType<typeof AppDemoModel>>;
export class AppDemoModel extends Model {
declare id: string;
declare title: string;
declare description: string;
declare summary: string;
declare data: AppDemoData;
declare tags: string[];
declare version: string;
declare uid: string;
declare createdAt: Date;
declare updatedAt: Date;
}
AppDemoModel.init(
{
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
},
title: {
type: DataTypes.TEXT,
defaultValue: '',
},
description: {
type: DataTypes.TEXT,
defaultValue: '',
},
summary: {
type: DataTypes.TEXT,
defaultValue: '',
},
tags: {
type: DataTypes.JSONB,
defaultValue: [],
},
version: {
type: DataTypes.INTEGER,
defaultValue: 0,
},
data: {
type: DataTypes.JSONB,
defaultValue: {},
},
uid: {
type: DataTypes.UUID,
allowNull: false,
},
},
{
sequelize,
tableName: 'kv_app_demo',
paranoid: true,
},
);
AppDemoModel.sync({ alter: true, logging: false }).catch((e) => {
console.error('AppDemoModel sync', e);
});