feat(core): Add endpoint to create free AI credits (#12362)

This commit is contained in:
Ricardo Espinoza
2024-12-27 09:46:57 -05:00
committed by GitHub
parent c00b95e08f
commit ac4e042231
19 changed files with 258 additions and 34 deletions
@@ -14,7 +14,8 @@ import { AiController, type FlushableResponse } from '../ai.controller';
describe('AiController', () => {
const aiService = mock<AiService>();
const controller = new AiController(aiService);
const controller = new AiController(aiService, mock(), mock());
const request = mock<AuthenticatedRequest>({
user: { id: 'user123' },
+47 -2
View File
@@ -1,19 +1,32 @@
import { AiChatRequestDto, AiApplySuggestionRequestDto, AiAskRequestDto } from '@n8n/api-types';
import {
AiChatRequestDto,
AiApplySuggestionRequestDto,
AiAskRequestDto,
AiFreeCreditsRequestDto,
} from '@n8n/api-types';
import type { AiAssistantSDK } from '@n8n_io/ai-assistant-sdk';
import { Response } from 'express';
import { strict as assert } from 'node:assert';
import { WritableStream } from 'node:stream/web';
import { FREE_AI_CREDITS_CREDENTIAL_NAME, OPEN_AI_API_CREDENTIAL_TYPE } from '@/constants';
import { CredentialsService } from '@/credentials/credentials.service';
import { Body, Post, RestController } from '@/decorators';
import { InternalServerError } from '@/errors/response-errors/internal-server.error';
import type { CredentialRequest } from '@/requests';
import { AuthenticatedRequest } from '@/requests';
import { AiService } from '@/services/ai.service';
import { UserService } from '@/services/user.service';
export type FlushableResponse = Response & { flush: () => void };
@RestController('/ai')
export class AiController {
constructor(private readonly aiService: AiService) {}
constructor(
private readonly aiService: AiService,
private readonly credentialsService: CredentialsService,
private readonly userService: UserService,
) {}
@Post('/chat', { rateLimit: { limit: 100 } })
async chat(req: AuthenticatedRequest, res: FlushableResponse, @Body payload: AiChatRequestDto) {
@@ -64,4 +77,36 @@ export class AiController {
throw new InternalServerError(e.message, e);
}
}
@Post('/free-credits')
async aiCredits(req: AuthenticatedRequest, _: Response, @Body payload: AiFreeCreditsRequestDto) {
try {
const aiCredits = await this.aiService.createFreeAiCredits(req.user);
const credentialProperties: CredentialRequest.CredentialProperties = {
name: FREE_AI_CREDITS_CREDENTIAL_NAME,
type: OPEN_AI_API_CREDENTIAL_TYPE,
data: {
apiKey: aiCredits.apiKey,
url: aiCredits.url,
},
isManaged: true,
projectId: payload?.projectId,
};
const newCredential = await this.credentialsService.createCredential(
credentialProperties,
req.user,
);
await this.userService.updateSettings(req.user.id, {
userClaimedAiCredits: true,
});
return newCredential;
} catch (e) {
assert(e instanceof Error);
throw new InternalServerError(e.message, e);
}
}
}