@@ -41,6 +41,11 @@ interface INewApiWrappedResponse<T> {
|
||||
success?: boolean;
|
||||
}
|
||||
|
||||
interface INewApiTokenKeyData {
|
||||
/** NewAPI 返回的完整 Token Key,仅允许服务端内部使用 */
|
||||
key: string;
|
||||
}
|
||||
|
||||
const AI_ART_STUDIO_TOKEN_PAYLOAD = {
|
||||
remain_quota: 0,
|
||||
remain_amount: 0,
|
||||
@@ -58,8 +63,8 @@ const AI_ART_STUDIO_TOKEN_PAYLOAD = {
|
||||
export const ensureAiArtStudioToken = async (
|
||||
event: H3Event
|
||||
): Promise<IUserReadyData> => {
|
||||
const hasToken = await hasActiveAiArtStudioToken(event);
|
||||
if (hasToken) {
|
||||
const token = await findActiveAiArtStudioToken(event);
|
||||
if (token) {
|
||||
return {
|
||||
ready: true,
|
||||
created: false
|
||||
@@ -74,8 +79,45 @@ export const ensureAiArtStudioToken = async (
|
||||
};
|
||||
};
|
||||
|
||||
/** 确保 AIArtStudio Token 可用,并获取完整 key,完整 key 不允许透出到前端 */
|
||||
export const getAiArtStudioTokenKey = async (
|
||||
event: H3Event
|
||||
): Promise<string> => {
|
||||
let token = await findActiveAiArtStudioToken(event);
|
||||
|
||||
if (!token) {
|
||||
await createAiArtStudioToken(event);
|
||||
token = await findActiveAiArtStudioToken(event);
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
throw createError({
|
||||
statusCode: 502,
|
||||
statusMessage: "环境初始化失败"
|
||||
});
|
||||
}
|
||||
|
||||
const response = await newApiAuthedFetch<
|
||||
INewApiWrappedResponse<INewApiTokenKeyData>
|
||||
>(event, `/api/token/${token.id}/key`, {
|
||||
method: "POST"
|
||||
});
|
||||
const data = unwrapNewApiResponse(response, "环境读取失败");
|
||||
|
||||
if (typeof data.key !== "string" || !data.key) {
|
||||
throw createError({
|
||||
statusCode: 502,
|
||||
statusMessage: "环境读取失败"
|
||||
});
|
||||
}
|
||||
|
||||
return data.key;
|
||||
};
|
||||
|
||||
/** 分页读取 Token 列表,只认名称为 AIArtStudio 且状态启用的未删除 Token */
|
||||
const hasActiveAiArtStudioToken = async (event: H3Event): Promise<boolean> => {
|
||||
const findActiveAiArtStudioToken = async (
|
||||
event: H3Event
|
||||
): Promise<INewApiTokenItem | null> => {
|
||||
let page = 1;
|
||||
let total = Number.POSITIVE_INFINITY;
|
||||
|
||||
@@ -87,15 +129,16 @@ const hasActiveAiArtStudioToken = async (event: H3Event): Promise<boolean> => {
|
||||
});
|
||||
const data = unwrapNewApiResponse(response, "环境检查失败");
|
||||
|
||||
if (data.items.some(isActiveAiArtStudioToken)) {
|
||||
return true;
|
||||
const token = data.items.find(isActiveAiArtStudioToken);
|
||||
if (token) {
|
||||
return token;
|
||||
}
|
||||
|
||||
total = data.total;
|
||||
page += 1;
|
||||
}
|
||||
|
||||
return false;
|
||||
return null;
|
||||
};
|
||||
|
||||
/** 创建默认 AIArtStudio Token,参数固定,避免 handler 内重复维护 */
|
||||
|
||||
Reference in New Issue
Block a user