Skip to content

Commit

Permalink
fix: view schema with answers and comments
Browse files Browse the repository at this point in the history
feat: vote answers
  • Loading branch information
Danielzxccc committed Dec 19, 2023
1 parent 673500b commit 4147e84
Show file tree
Hide file tree
Showing 9 changed files with 689 additions and 105 deletions.
30 changes: 30 additions & 0 deletions draft_sql/draft-schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
CREATE TABLE answer_votes(
id SERIAL PRIMARY KEY,
answerid INT NOT NULL,
userid INT NOT NULL,
type TEXT NOT NULL,
createdAt timestamp DEFAULT CURRENT_TIMESTAMP,
updatedAt timestamp DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (answerid) REFERENCES forums_answers(id) ON DELETE CASCADE,
FOREIGN KEY (userid) REFERENCES users(id) ON DELETE CASCADE,
UNIQUE (answerid, userid)
);


CREATE TABLE community_events(
id SERIAL PRIMARY KEY,
userid INT NOT NULL,
event_name TEXT,
event_location TEXT,
event_date timestamp,
scope TEXT DEFAULT 'Private', --if private or public
details TEXT, --description
imagesrc TEXT,
longitude DOUBLE PRECISION,
latitude DOUBLE PRECISION,
createdAt timestamp DEFAULT CURRENT_TIMESTAMP,
updatedAt timestamp DEFAULT CURRENT_TIMESTAMP,
status BOOLEAN DEFAULT TRUE,
FOREIGN KEY (userid) REFERENCES users(id) ON DELETE CASCADE
);

3 changes: 2 additions & 1 deletion src/config/database.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Kysely, PostgresDialect } from 'kysely'
import { Kysely, ParseJSONResultsPlugin, PostgresDialect } from 'kysely'
import { DB } from 'kysely-codegen'
import { Pool } from 'pg'
import * as dotenv from 'dotenv'
Expand All @@ -11,6 +11,7 @@ export const db = new Kysely<DB>({
connectionString: process.env.DATABASE_URL,
}),
}),
// plugins: [new ParseJSONResultsPlugin()],
log(event) {
if (event.level === 'query') {
log.info(event.query.sql)
Expand Down
33 changes: 33 additions & 0 deletions src/modules/AWS-Bucket/UploadService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,36 @@ export async function getObjectSignedUrl(key: string) {

return url
}

// Function to replace avatars in a JSON object with the corresponding URLs
export async function replaceAvatarsWithUrls(jsonObject: any): Promise<any> {
const replaceAvatarAsync = async (avatarKey: string) => {
const avatarUrl = await getObjectUrl(avatarKey)
return avatarUrl
}

const replaceAvatarsRecursively = async (obj: any): Promise<any> => {
if (obj instanceof Array) {
return Promise.all(obj.map(replaceAvatarsRecursively))
} else if (obj !== null && typeof obj === 'object') {
const promises = Object.entries(obj).map(async ([key, value]) => {
if (key === 'avatar' && typeof value === 'string') {
// If the property is 'avatar' and the value is a string, replace it
return { [key]: await replaceAvatarAsync(value) }
} else {
// Recursively replace avatars in nested objects
return { [key]: await replaceAvatarsRecursively(value) }
}
})

const replacedProperties = await Promise.all(promises)
return Object.assign({}, ...replacedProperties)
} else {
return obj
}
}

// Start the replacement process
const replacedObject = await replaceAvatarsRecursively(jsonObject)
return replacedObject
}
30 changes: 26 additions & 4 deletions src/modules/Forums/ForumsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,19 @@ export async function viewQuestion(req: SessionRequest, res: Response) {
offset,
perPage,
ip,
user
user,
query.filter
)

res.status(200).json(question)
const totalPages = Math.ceil(Number(question.total.count) / perPage)
res.status(200).json({
question: question.data,
pagination: {
page: pageNumber,
per_page: perPage,
total_pages: totalPages,
total_records: Number(question.total.count),
},
})
} catch (error) {
errorHandler(res, error)
}
Expand Down Expand Up @@ -89,7 +98,7 @@ export async function voteQuestion(req: SessionRequest, res: Response) {

const vote = await Interactor.voteQuestion(params.id, userid, body.type)

res.status(200).json({ message: `${body.type} successfully`, vote })
res.status(201).json({ message: `${body.type} successfully`, vote })
} catch (error) {
errorHandler(res, error)
}
Expand Down Expand Up @@ -136,3 +145,16 @@ export async function createNewComment(req: SessionRequest, res: Response) {
errorHandler(res, error)
}
}

export async function voteAnswer(req: SessionRequest, res: Response) {
try {
const userid = req.session.userid
const { body, params } = await zParse(Schema.VoteAnswerSchema, req)

const vote = await Interactor.voteAnswer(params.id, userid, body)

res.status(201).json({ message: 'Voted Answer Successfully', data: vote })
} catch (error) {
errorHandler(res, error)
}
}
32 changes: 25 additions & 7 deletions src/modules/Forums/ForumsInteractor.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import HttpError from '../../utils/HttpError'
import { NewQuestion, Question } from '../../types/DBTypes'
import { NewQuestion, NewVoteQuestion, Question } from '../../types/DBTypes'
import dbErrorHandler from '../../utils/dbErrorHandler'
import * as Service from './ForumsService'
import { ForumsContent } from './../../schema/ForumsSchema'
import { getObjectUrl, uploadFiles } from '../AWS-Bucket/UploadService'
import {
getObjectUrl,
replaceAvatarsWithUrls,
uploadFiles,
} from '../AWS-Bucket/UploadService'
import { deleteFile } from '../../utils/file'
import { viewsLimitter } from '../../middleware/ViewsLimitter'

Expand All @@ -12,7 +16,8 @@ export async function viewQuestion(
offset: number,
perPage: number,
ip: string,
user: string
user: string,
filter?: 'newest' | 'top'
) {
// view limitting logic
const isViewed = await viewsLimitter({ id, ip, user })
Expand All @@ -25,13 +30,16 @@ export async function viewQuestion(

if (isNaN(questionId)) throw new HttpError('Not a valid ID', 400)

const question = await Service.viewQuestion(id, offset, perPage)
const [data, total] = await Promise.all([
Service.viewQuestion(id, offset, perPage, user, filter),
Service.getTotalAnswers(id),
])

if (!question) throw new HttpError('Question Not Found', 404)
if (!data) throw new HttpError('Question Not Found', 404)

question.user.avatar = getObjectUrl(question.user.avatar)
const formattedQuestion = await replaceAvatarsWithUrls(data)

return question
return { data: formattedQuestion, total }
}

export async function listQuestions(
Expand Down Expand Up @@ -151,3 +159,13 @@ export async function voteQuestion(

return data
}

export async function voteAnswer(
answerid: string,
userid: string,
vote: NewVoteQuestion
) {
const data = { ...vote, answerid, userid }
const votedQuestion = await Service.voteAnswer(data)
return votedQuestion
}
Loading

0 comments on commit 4147e84

Please sign in to comment.