Skip to content

Commit

Permalink
issue#21 add chat apis
Browse files Browse the repository at this point in the history
  • Loading branch information
ZHallen122 committed Oct 25, 2024
1 parent 1623503 commit f52f53a
Show file tree
Hide file tree
Showing 5 changed files with 156 additions and 7 deletions.
36 changes: 35 additions & 1 deletion backend/src/chat/chat.model.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,44 @@
import { Field, InputType, ObjectType } from '@nestjs/graphql';
import { Field, InputType, ObjectType, ID } from '@nestjs/graphql';
import { SystemBaseModel } from 'src/system-base-model/system-base.model';

export enum Role {
User = 'User',
Model = 'Model'
}

@ObjectType()
export class Message extends SystemBaseModel {
@Field(() => ID)
id: string;

@Field()
content: string;

@Field(() => Role)
role: Role;

@Field({ nullable: true })
modelId?: string;
}

@ObjectType()
export class Chat extends SystemBaseModel {
@Field(() => ID)
id: string;

@Field({ nullable: true })
title: string;

@Field(() => [Message])
messages: Message[];
}

@ObjectType('ChatCompletionDeltaType')
class ChatCompletionDelta {
@Field({ nullable: true })
content?: string;
}

@ObjectType('ChatCompletionChunkType')
export class ChatCompletionChunk {
@Field()
Expand Down
4 changes: 2 additions & 2 deletions backend/src/chat/chat.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { HttpModule } from '@nestjs/axios';
import { ChatResolver } from './chat.resolver';
import { ChatProxyService } from './chat.service';
import { ChatProxyService, ChatService } from './chat.service';

@Module({
imports: [HttpModule],
providers: [ChatResolver, ChatProxyService],
providers: [ChatResolver, ChatProxyService, ChatService],
})
export class ChatModule {}
50 changes: 47 additions & 3 deletions backend/src/chat/chat.resolver.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { Resolver, Subscription, Args } from '@nestjs/graphql';
import { Resolver, Subscription, Args, Query, Mutation } from '@nestjs/graphql';
import { ChatCompletionChunk, ChatInput } from './chat.model';
import { ChatProxyService } from './chat.service';
import { ChatProxyService, ChatService } from './chat.service';
import { title } from 'process';
import { Chat, Message } from './chat.model';
import { User } from 'src/user/user.model';

@Resolver('Chat')
export class ChatResolver {
constructor(private chatProxyService: ChatProxyService) {}
constructor(
private chatProxyService: ChatProxyService,
private chatService: ChatService,
) {}

@Subscription(() => ChatCompletionChunk, {
nullable: true,
Expand All @@ -24,4 +30,42 @@ export class ChatResolver {
throw new Error('Chat stream failed');
}
}

@Query(() => [Message])
async getChatHistory(@Args('chatId') chatId: string): Promise<Message[]> {
return this.chatService.getChatHistory(chatId);
}

@Query(() => Chat, { nullable: true })
async getChatDetails(@Args('chatId') chatId: string): Promise<Chat> {
return this.chatService.getChatDetails(chatId);
}

// @Query(() => [Message])
// getModelTags(@Args('chatId') chatId: string): Message[] {
// return this.chatService.getChatHistory(chatId);
// }

@Mutation(() => Chat)
async createChat(): Promise<Chat> {
return this.chatService.createChat();
}

@Mutation(() => Boolean)
async deleteChat(@Args('chatId') chatId: string): Promise<boolean> {
return this.chatService.deleteChat(chatId);
}

@Mutation(() => Boolean)
async clearChatHistory(@Args('chatId') chatId: string): Promise<boolean> {
return this.chatService.clearChatHistory(chatId);
}

@Mutation(() => Chat, { nullable: true })
async updateChatTitle(
@Args('chatId') chatId: string,
@Args('title') title: string,
): Promise<Chat> {
return this.chatService.updateChatTitle(chatId, title);
}
}
69 changes: 68 additions & 1 deletion backend/src/chat/chat.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ChatCompletionChunk } from './chat.model';
import { ChatCompletionChunk, Chat, Message } from './chat.model';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from 'src/user/user.model';

type CustomAsyncIterableIterator<T> = AsyncIterator<T> & {
[Symbol.asyncIterator](): AsyncIterableIterator<T>;
Expand Down Expand Up @@ -132,3 +135,67 @@ export class ChatProxyService {
);
}
}

@Injectable()
export class ChatService {
constructor(
@InjectRepository(Chat)
private chatRepository: Repository<Chat>,
@InjectRepository(User)
private userRepository: Repository<User>,
) {}

async getChatHistory(chatId: string): Promise<Message[]> {
const chat = await this.chatRepository.findOne({
where: { id: chatId },
relations: ['messages'],
});
return chat ? chat.messages : [];
}

async getChatDetails(chatId: string): Promise<Chat> {
return this.chatRepository.findOne({
where: { id: chatId },
relations: ['messages'],
});
}

async createChat(): Promise<Chat> {
const newChat = this.chatRepository.create({
title: 'New Chat',
messages: [],
createdAt: new Date(),
updatedAt: new Date(),
});
return await this.chatRepository.save(newChat);
}

async deleteChat(chatId: string): Promise<boolean> {
const result = await this.chatRepository.delete(chatId);
return result.affected > 0;
}

async clearChatHistory(chatId: string): Promise<boolean> {
const chat = await this.chatRepository.findOne({
where: { id: chatId },
relations: ['messages'],
});
if (chat) {
chat.messages = [];
chat.updatedAt = new Date();
await this.chatRepository.save(chat);
return true;
}
return false;
}

async updateChatTitle(chatId: string, title: string): Promise<Chat> {
const chat = await this.chatRepository.findOne({ where: { id: chatId } });
if (chat) {
chat.title = title;
chat.updatedAt = new Date();
return await this.chatRepository.save(chat);
}
return null;
}
}
4 changes: 4 additions & 0 deletions backend/src/user/user.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ObjectType, Field, ID } from '@nestjs/graphql';
import { IsEmail } from 'class-validator';
import { Role } from 'src/auth/role/role.model';
import { SystemBaseModel } from 'src/system-base-model/system-base.model';
import { Chat } from 'src/chat/chat.model';
import {
Entity,
PrimaryGeneratedColumn,
Expand Down Expand Up @@ -29,6 +30,9 @@ export class User extends SystemBaseModel {
@IsEmail()
email: string;

@Field(() => [Chat])
chats: Chat[];

@ManyToMany(() => Role)
@JoinTable({
name: 'user_roles',
Expand Down

0 comments on commit f52f53a

Please sign in to comment.