Skip to content

Commit

Permalink
fut: add prisma provider
Browse files Browse the repository at this point in the history
  • Loading branch information
fulcanelly committed Nov 14, 2024
1 parent bbc3269 commit 6cb2f14
Show file tree
Hide file tree
Showing 5 changed files with 249 additions and 503 deletions.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "chat-toolkit",
"version": "0.2.2",
"version": "0.2.3",
"description": "",
"author": "",
"private": false,
Expand All @@ -24,9 +24,11 @@
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"@prisma/client": "5.22.0",
"@types/ramda": "^0.30.2",
"dotenv": "^16.4.5",
"moment": "^2.30.1",
"prisma": "^5.22.0",
"ramda": "^0.30.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
Expand Down
35 changes: 35 additions & 0 deletions prisma/schema/chat-toolkits.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

model User {
id BigInt @id
first_name String
state State?
}

model State {
id Int @id @default(autoincrement())
state String
arguments String?
on_return_switch_to String?
on_return_switch_args String?
created_at DateTime
user User @relation(fields: [userId], references: [id])
events Event[]
userId BigInt @unique
}

model Event {
id Int @id @default(autoincrement())
eventName String
data String?
created_at DateTime
State State? @relation(fields: [stateId], references: [id])
stateId Int?
}
9 changes: 9 additions & 0 deletions prisma/schema/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
generator client {
provider = "prisma-client-js"
previewFeatures = ["prismaSchemaFolder"]
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
127 changes: 127 additions & 0 deletions src/providers/prisma.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import { superjson } from "@/lib/superjson";
import { PrismaClient, User } from "@prisma/client";
import { Context } from "chat-toolkit";
import { RecordedEvent, TransactionT } from 'chat-toolkit/src/state/state';


type DefaultPrismaStateManagerImplementation = (prisma: PrismaClient) => (params: { currentUser: User; defaultState: string; }) => Context['manage']
type FindOrCreateUserPrisma = (prisma: PrismaClient) => (user_id: any, first_name?: any) => Promise<User>

export const defaultPrismaStateManagerImplementation: DefaultPrismaStateManagerImplementation
= prisma => params => {
const { currentUser, defaultState } = params;

const cachedCurrentState = {
async set(state: string, args: any, session?: TransactionT) {
console.warn("CREATE STATE")

await prisma.state.create({
data: {
state: state,
arguments: superjson.stringify(args),
created_at: new Date(),
userId: currentUser.id
}
});
},

async get(it?: TransactionT) {
console.log("Getting current state");
return await findCurrentState(it);
}
};

const findCurrentState = (session?: TransactionT) => prisma.state.findFirst({ where: { userId: currentUser.id } });

const state: Context['manage']['state'] = {
async save(state: string, args: any, params): Promise<void> {
await cachedCurrentState.set(state, args, params?.session);
},

default(): string {
return defaultState;
},

async current(): Promise<string | undefined> {
const result = await cachedCurrentState.get();
return result?.state;
},

async currentFull(): Promise<any | undefined> {
return await cachedCurrentState.get();
},

async delete(params): Promise<void> {
await prisma.state.delete({
where: {
userId: currentUser.id
}
});
},
};

const events: Context['manage']['events'] = {
async loadAll() {
console.warn("load all events")

const currenState = await cachedCurrentState.get();

const all = await prisma.event.findMany({
where: {
stateId: currenState.id
},
orderBy: {
created_at: 'asc'
}
});

return all.map(({ eventName, data }) => ({ eventName, data: data ? superjson.parse(data) : undefined })) as RecordedEvent[];
},

async save(event) {
console.warn("save event")

const state = await cachedCurrentState.get();

await prisma.event.create({
data: {
eventName: event.eventName,
data: superjson.stringify(event.data),
created_at: new Date(),
stateId: state.id,
}
});
},

async deleteAll(params) {
console.warn("DELETE ALL events")
const state = await cachedCurrentState.get();

await prisma.event.deleteMany({
where: { stateId: state.id }
});
}
};

return {
state,
events
};
}


export const findOrCreateUserPrisma: FindOrCreateUserPrisma
= (prisma) => (user_id: any, first_name = '') =>
prisma.user.upsert({
create: {
id: user_id,
first_name,
},
update: {
first_name
},
where: {
id: user_id
}
})

Loading

0 comments on commit 6cb2f14

Please sign in to comment.