Skip to content

Commit

Permalink
Merge pull request #4 from Muimi-Chat/staging
Browse files Browse the repository at this point in the history
1 Database table for configuration (should only ever have 1 row)
  • Loading branch information
wqyeo authored Jul 6, 2024
2 parents d00cdfe + 4ff0c3a commit 079e60f
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 13 deletions.
3 changes: 0 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,6 @@ OPENAI_ORGANIZATION_ID=org-id
# python -c "import secrets; print('Pepper:', secrets.token_hex(16))"
HASHING_PEPPER=asdasdasdasdasdsadas

# Default starting token amount by users.
DEFAULT_STARTING_TOKEN=25000

############
# Database #
############
Expand Down
3 changes: 0 additions & 3 deletions src/api/controllers/getConversations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ import { Request, Response } from 'express';
import { createClient } from 'redis';
import insertLog from '../repositories/insertLog';
import fetchUserInformation from '../services/fetchUserInformation';
import selectAccountByUUID from '../repositories/selectAccountByUUID';
import insertAccountWithUUID from '../repositories/insertAccountWithUUID';
import { uuid } from 'drizzle-orm/pg-core';
import { REDIS_CONNECTION_STRING } from 'src/configs/redisConnectionString';
import selectConversationsByUserID from '../repositories/selectConversationsByUserID';
import { selectMessagesByConversationID } from '../repositories/selectMessagesByConversationID';
Expand Down
10 changes: 7 additions & 3 deletions src/api/controllers/getTokenCountController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import selectAccountByUUID from '../repositories/selectAccountByUUID';
import insertAccountWithUUID from '../repositories/insertAccountWithUUID';
import { uuid } from 'drizzle-orm/pg-core';
import { REDIS_CONNECTION_STRING } from 'src/configs/redisConnectionString';
import { db } from 'src/db';
import { configuration } from 'src/schema';

export default async function getTokenCountController(req: Request, res: Response) {
const client = createClient({
Expand Down Expand Up @@ -62,10 +64,12 @@ export default async function getTokenCountController(req: Request, res: Respons
let isFreeTokenUser = false
const accountObject = await selectAccountByUUID(userUUID)
if (accountObject.length <= 0) {
await insertAccountWithUUID(userUUID)
await insertLog(`Created new user in database :: ${uuid}`, "INFO");
const defaultTokenCount = parseInt(process.env.DEFAULT_STARTING_TOKEN || "25000") ?? 25000;
const globalConfig = await db.select().from(configuration);
const defaultTokenCount = globalConfig[0].defaultUsersTokenCount;
tokenCount = defaultTokenCount

await insertAccountWithUUID(userUUID, tokenCount)
await insertLog(`Created new user in database :: ${uuid}`, "INFO");
} else {
tokenCount = accountObject[0].token
isFreeTokenUser = accountObject[0].freeTokenUsage
Expand Down
6 changes: 4 additions & 2 deletions src/api/repositories/insertAccountWithUUID.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ import { account } from "src/schema";
import insertLog from "./insertLog";

export default async function insertAccountWithUUID(
uuid: string
uuid: string,
newTokenCount: number
) {
try {
return await db.insert(account).values({
id: uuid
id: uuid,
token: newTokenCount
})
} catch (err) {
const message = `Failed to insert account with UUID (${uuid}) :: ${err}`
Expand Down
24 changes: 24 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import express from 'express';
import cors from 'cors';

import { db } from "src/db";
import { configuration } from "src/schema";

import tokenRoutes from './api/routes/tokenRoutes'
import conversationRoutes from './api/routes/conversationRoutes'
Expand All @@ -9,6 +11,7 @@ import chatMessageConsumer from './api/consumers/chatMessageConsumer';
const app = express();

import expressWs from 'express-ws';
import insertLog from './api/repositories/insertLog';
expressWs(app);

const port = 3000;
Expand Down Expand Up @@ -36,6 +39,27 @@ wsRouter.ws("/", (ws, req) => {

app.use('/api-chat/chat', wsRouter);

async function _initalizeConfiguration() {
const rows = await db.select().from(configuration);

if (rows.length <= 0) {
await db.insert(configuration).values({
defaultUsersTokenCount: 25000
})
await insertLog("Created configuration", "INFO")
console.log("Missing configuration, added.")
} else if (rows.length >= 2) {
await insertLog("There is more than one configuration row in the database. This should not happen!", "WARNING")
console.warn("More than 1 configuration row exists!")
} else {
console.log("Configuration exists!")
}
}

app.listen(port, () => {
console.log(`Server is running on port ${port}`);

_initalizeConfiguration().then(() => {
console.log("Checked configuration")}
)
});
7 changes: 5 additions & 2 deletions src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@ Index name should be `wrsm_sessionid_idx`

import { integer, pgTable, uuid, text, index, uniqueIndex, varchar, date, timestamp, primaryKey, pgEnum, serial, smallint, bigint, boolean } from "drizzle-orm/pg-core";

const defaultTokenCount = parseInt(process.env.DEFAULT_STARTING_TOKEN || "25000") ?? 25000;
export const configuration = pgTable('configuration', {
id: serial('id').primaryKey(),
defaultUsersTokenCount: integer('default_users_token_count').notNull()
})

export const account = pgTable('account', {
id: uuid('id').primaryKey(),
token: integer('token').default(defaultTokenCount).notNull(),
token: integer('token').notNull(),
freeTokenUsage: boolean('free_token_usage').default(false).notNull()
});

Expand Down

0 comments on commit 079e60f

Please sign in to comment.