perf: completion chatId

This commit is contained in:
archer
2023-07-23 20:07:35 +08:00
parent b7d18e38d1
commit 67e10d6f2c
35 changed files with 447 additions and 385 deletions

View File

@@ -0,0 +1,61 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@/service/response';
import { authUser } from '@/service/utils/auth';
import { connectToDatabase, TrainingData, User, promotionRecord, Chat } from '@/service/mongo';
import { PRICE_SCALE } from '@/constants/common';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
await authUser({ req, authRoot: true });
await connectToDatabase();
const { limit = 1000 } = req.body as { limit: number };
let skip = 0;
const total = await Chat.countDocuments({
chatId: { $exists: false }
});
let promise = Promise.resolve();
console.log(total);
for (let i = 0; i < total; i += limit) {
const skipVal = skip;
skip += limit;
promise = promise
.then(() => init(limit, skipVal))
.then(() => {
console.log(skipVal);
});
}
await promise;
jsonRes(res, {});
} catch (error) {
jsonRes(res, {
code: 500,
error
});
}
}
async function init(limit: number, skip: number) {
// 遍历 app
const chats = await Chat.find(
{
chatId: { $exists: false }
},
'_id'
)
.limit(limit)
.skip(skip);
await Promise.all(
chats.map((chat) =>
Chat.findByIdAndUpdate(chat._id, {
chatId: String(chat._id),
source: 'online'
})
)
);
}

View File

@@ -1,47 +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 { authUser } from '@/service/utils/auth';
import { connectToDatabase, TrainingData, User, promotionRecord } from '@/service/mongo';
import { PRICE_SCALE } from '@/constants/common';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
await authUser({ req, authRoot: true });
await connectToDatabase();
// 计算剩余金额
const countResidue: { userId: string; totalAmount: number }[] = await promotionRecord.aggregate(
[
{
$group: {
_id: '$userId', // Group by userId
totalAmount: { $sum: '$amount' } // Calculate the sum of amount field
}
},
{
$project: {
_id: false, // Exclude _id field
userId: '$_id', // Include userId field
totalAmount: true // Include totalAmount field
}
}
]
);
await Promise.all(
countResidue.map((item) =>
User.findByIdAndUpdate(item.userId, {
$inc: { balance: item.totalAmount * PRICE_SCALE }
})
)
);
jsonRes(res, { data: countResidue });
} catch (error) {
jsonRes(res, {
code: 500,
error
});
}
}