perf: plus api

This commit is contained in:
archer
2023-08-22 17:45:18 +08:00
parent 7a231c6501
commit a5f8fae3f2
25 changed files with 136 additions and 499 deletions

View File

@@ -0,0 +1,44 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@/service/response';
import { request } from '@/api/service/request';
import type { Method } from 'axios';
import { connectToDatabase } from '@/service/mongo';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
await connectToDatabase();
const method = (req.method || 'POST') as Method;
const { path = [], ...query } = req.query as any;
const url = `/${path?.join('/')}`;
if (!url) {
throw new Error('url is empty');
}
const data = {
...req.body,
...query
};
const repose = await request(
url,
data,
{
// @ts-ignore
headers: req.headers
},
method
);
jsonRes(res, {
data: repose
});
} catch (error) {
jsonRes(res, {
code: 500,
error
});
}
}

View File

@@ -97,7 +97,6 @@ export async function getInitConfig() {
global.chatModels = res.ChatModels || defaultChatModels;
global.qaModels = res.QAModels || defaultQAModels;
global.vectorModels = res.VectorModels || defaultVectorModels;
global.systemPlugins = res.plugins || {};
} catch (error) {
setDefaultData();
console.log('get init config error, set default', error);
@@ -110,5 +109,4 @@ export function setDefaultData() {
global.chatModels = defaultChatModels;
global.qaModels = defaultQAModels;
global.vectorModels = defaultVectorModels;
global.systemPlugins = {};
}

View File

@@ -0,0 +1,30 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@/service/response';
import { TrainingData } from '@/service/mongo';
import { startQueue } from '@/service/utils/tools';
import { authUser } from '@/service/utils/auth';
export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
try {
const { userId } = await authUser({ req, authToken: true });
await unlockTask(userId);
} catch (error) {}
jsonRes(res);
}
async function unlockTask(userId: string) {
try {
await TrainingData.updateMany(
{
userId
},
{
lockTime: new Date('2000/1/1')
}
);
startQueue();
} catch (error) {
unlockTask(userId);
}
}

View File

@@ -1,64 +0,0 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@/service/response';
import { User } from '@/service/models/user';
import { connectToDatabase } from '@/service/mongo';
import { generateToken, setCookie } from '@/service/utils/tools';
import { UserAuthTypeEnum } from '@/constants/common';
import { authCode } from '@/service/api/plugins';
export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
try {
const { username, code, password, inviterId } = req.body;
if (!username || !code || !password) {
throw new Error('缺少参数');
}
await connectToDatabase();
// 验证码校验
await authCode({
username,
type: UserAuthTypeEnum.register,
code
});
// 重名校验
const authRepeat = await User.findOne({
username
});
if (authRepeat) {
throw new Error('该用户已被注册');
}
const response = await User.create({
username,
password,
inviterId: inviterId ? inviterId : undefined
});
// 根据 id 获取用户信息
const user = await User.findById(response._id);
if (!user) {
throw new Error('获取用户信息异常');
}
const token = generateToken(user._id);
setCookie(res, token);
jsonRes(res, {
data: {
user,
token
}
});
} catch (err) {
jsonRes(res, {
code: 500,
error: err
});
}
}

View File

@@ -1,65 +0,0 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@/service/response';
import { User } from '@/service/models/user';
import { connectToDatabase } from '@/service/mongo';
import { UserAuthTypeEnum } from '@/constants/common';
import { generateToken, setCookie } from '@/service/utils/tools';
import { authCode } from '@/service/api/plugins';
export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
try {
const { username, code, password } = req.body;
if (!username || !code || !password) {
throw new Error('缺少参数');
}
await connectToDatabase();
// 验证码校验
await authCode({
username,
code,
type: UserAuthTypeEnum.findPassword
});
if (!authCode) {
throw new Error('验证码错误');
}
// 更新对应的记录
await User.updateOne(
{
username
},
{
password
}
);
// 根据 username 获取用户信息
const user = await User.findOne({
username
});
if (!user) {
throw new Error('获取用户信息异常');
}
const token = generateToken(user._id);
setCookie(res, token);
jsonRes(res, {
data: {
user,
token
}
});
} catch (err) {
jsonRes(res, {
code: 500,
error: err
});
}
}

View File

@@ -1,112 +0,0 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@/service/response';
import { User, Pay, TrainingData } from '@/service/mongo';
import { authUser } from '@/service/utils/auth';
import { PaySchema } from '@/types/mongoSchema';
import dayjs from 'dayjs';
import { startQueue } from '@/service/utils/tools';
import { getWxPayQRResult } from '@/service/api/plugins';
/* 校验支付结果 */
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const { payId } = req.query as { payId: string };
const { userId } = await authUser({ req, authToken: true });
// 查找订单记录校验
const payOrder = await Pay.findById<PaySchema>(payId);
if (!payOrder) {
throw new Error('订单不存在');
}
if (payOrder.status !== 'NOTPAY') {
throw new Error('订单已结算');
}
// 获取当前用户
const user = await User.findById(userId);
if (!user) {
throw new Error('找不到用户');
}
const payRes = await getWxPayQRResult(payOrder.orderId);
if (payRes.trade_state === 'SUCCESS') {
// 订单已支付
try {
// 更新订单状态. 如果没有合适的订单,说明订单重复了
const updateRes = await Pay.updateOne(
{
_id: payId,
status: 'NOTPAY'
},
{
status: 'SUCCESS'
}
);
if (updateRes.modifiedCount === 1) {
// 给用户账号充钱
await User.findByIdAndUpdate(userId, {
$inc: { balance: payOrder.price }
});
unlockTask(userId);
return jsonRes(res, {
data: '支付成功'
});
}
} catch (error) {
console.log(error);
// roll back status
try {
await Pay.findByIdAndUpdate(payId, {
status: 'NOTPAY'
});
} catch (error) {}
}
return jsonRes(res, {
code: 500,
data: '更新订单失败,请重试'
});
}
// 校验下是否超过一天
const orderTime = dayjs(payOrder.createTime);
const diffInHours = dayjs().diff(orderTime, 'hours');
if (payRes.trade_state === 'CLOSED' || diffInHours > 24) {
// 订单已关闭
await Pay.findByIdAndUpdate(payId, {
status: 'CLOSED'
});
return jsonRes(res, {
code: 500,
data: '订单已过期'
});
}
throw new Error(payRes?.trade_state_desc || '订单无效');
} catch (err) {
// console.log(err);
jsonRes(res, {
code: 500,
error: err
});
}
}
async function unlockTask(userId: string) {
try {
await TrainingData.updateMany(
{
userId
},
{
lockTime: new Date('2000/1/1')
}
);
startQueue();
} catch (error) {
unlockTask(userId);
}
}

View File

@@ -1,37 +0,0 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@/service/response';
import { authUser } from '@/service/utils/auth';
import { Pay } from '@/service/mongo';
import { PRICE_SCALE } from '@/constants/common';
import { getWxPayQRUrl } from '@/service/api/plugins';
/* 获取支付二维码 */
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
let { amount = 0 } = req.query as { amount: string };
amount = +amount;
const { userId } = await authUser({ req, authToken: true });
const { code_url, orderId } = await getWxPayQRUrl(amount);
// add one pay record
const payOrder = await Pay.create({
userId,
price: amount * PRICE_SCALE,
orderId
});
jsonRes(res, {
data: {
payId: payOrder._id,
codeUrl: code_url
}
});
} catch (err) {
jsonRes(res, {
code: 500,
error: err
});
}
}

View File

@@ -39,7 +39,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
jsonRes(res, {
data: {
invitedAmount,
historyAmount: countHistory[0]?.totalAmount || 0
earningsAmount: countHistory[0]?.totalAmount || 0
}
});
} catch (err) {

View File

@@ -1,47 +0,0 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@/service/response';
import { UserAuthTypeEnum } from '@/constants/common';
import { authGoogleToken } from '@/utils/plugin/google';
import requestIp from 'request-ip';
import { sendCode } from '@/service/api/plugins';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const { username, type, googleToken } = req.body as {
username: string;
type: `${UserAuthTypeEnum}`;
googleToken: string;
};
if (!username || !type) {
throw new Error('缺少参数');
}
// google auth
global.systemEnv.googleServiceVerKey &&
(await authGoogleToken({
secret: global.systemEnv.googleServiceVerKey,
response: googleToken,
remoteip: requestIp.getClientIp(req) || undefined
}));
// register switch
if (type === UserAuthTypeEnum.register && !global.feConfigs?.show_register) {
throw new Error('Register is closed');
}
await sendCode({
username,
type
});
jsonRes(res, {
message: '发送验证码成功'
});
} catch (err) {
jsonRes(res, {
code: 500,
error: err
});
}
}