Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Build Session/Recording Page #24

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions db/models/Recording.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import * as typegoose from '@typegoose/typegoose'
import { modelOptions, prop } from '@typegoose/typegoose'
import Session from './Session'
import User from './User'

@modelOptions({ schemaOptions: { collection: 'Recording', versionKey: false, timestamps: true } })
class Recording {
@prop({ required: true })
public recordingId: string

@prop()
public recordingUrl: string

@prop({ ref: Session })
public sessionId: typegoose.Ref<Session>

@prop({ ref: User })
public userId: typegoose.Ref<User>
}

export default Recording
15 changes: 15 additions & 0 deletions db/models/Session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as typegoose from '@typegoose/typegoose'
import { modelOptions, prop } from '@typegoose/typegoose'

import User from './User'

@modelOptions({ schemaOptions: { collection: 'Session', versionKey: false, timestamps: true } })
class Session {
@prop({ required: true })
public name: string

@prop({ ref: User })
public userId: typegoose.Ref<User>
}

export default Session
4 changes: 2 additions & 2 deletions db/models/Topic.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { modelOptions, prop, getModelForClass } from '@typegoose/typegoose'
import { modelOptions, prop } from '@typegoose/typegoose'

@modelOptions({ schemaOptions: { collection: 'Topic', versionKey: false, timestamps: true } })
class Topic {
Expand All @@ -9,4 +9,4 @@ class Topic {
public image: string
}

export default getModelForClass(Topic)
export default Topic
4 changes: 2 additions & 2 deletions db/models/User.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { modelOptions, prop, getModelForClass } from '@typegoose/typegoose'
import { modelOptions, prop } from '@typegoose/typegoose'
import { defaultAvatarImg } from '@/util/constants'

@modelOptions({ schemaOptions: { versionKey: false, timestamps: false, _id: false } })
Expand Down Expand Up @@ -46,4 +46,4 @@ class User {
// public collectionId: typegoose.Ref<PlayerCollection>
}

export default getModelForClass(User)
export default User
10 changes: 10 additions & 0 deletions db/models/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { getModelForClass } from '@typegoose/typegoose'
import User from './User'
import Topic from './Topic'
import Session from './Session'
import Recording from './Recording'

export const UserModel = getModelForClass(User)
export const TopicModel = getModelForClass(Topic)
export const SessionModel = getModelForClass(Session)
export const RecordingModel = getModelForClass(Recording)
6 changes: 3 additions & 3 deletions helpers/APIHelper.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import User from '@/db/models/User'
import { UserModel } from '@/db/models'
import dbConnect from '@/db/dbConnect'
import { getServerSession } from 'next-auth/next'
import { authOptions } from '../pages/api/auth/[...nextauth]'
Expand All @@ -22,7 +22,7 @@ export const authorizeSession = async (
export const userIsAdmin = async (username: string, email: string) => {
await dbConnect()
if (username) {
const player = await User.findOne({ username: username, email: email })
const player = await UserModel.findOne({ username: username, email: email })
if (player) {
return player.isAdmin || false
} else {
Expand Down Expand Up @@ -50,7 +50,7 @@ export const authenticateKey = async (
return res.status(400).send(`Authentication Invalid. Job ${resource} was not processed`)
}
await dbConnect()
const admin = await User.findOne({ username: username, accessKey: accessKey })
const admin = await UserModel.findOne({ username: username, accessKey: accessKey })
if (!admin) {
console.warn(`Unauthorized. Job ${resource} was not processed`)
return res.status(401).send(`Unauthorized. Job ${resource} was not processed`)
Expand Down
19 changes: 14 additions & 5 deletions pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
import User from '@/db/models/User'
import dbConnect from '@/db/dbConnect'
import axios from 'axios'
import { userIsAdmin } from '@/helpers/APIHelper'
Expand Down Expand Up @@ -46,11 +45,21 @@ export const authOptions = {
const provider = credentials?.account?.provider?.toUpperCase()
const providerId = credentials?.account?.providerAccountId

const apiBaseUrl = process.env.NEXTAUTH_URL
console.log('baseUrl', apiBaseUrl)

console.log('well')
await dbConnect()
const potentialUser = await User.findOne({
username: username,
'provider.providerId': providerId,
})
console.log('poo')
console.log(`${apiBaseUrl}/api/users?username=${username}&providerId=${providerId}`)
const res = await axios.get(
`${apiBaseUrl}/api/users?username=${username}&providerId=${providerId}`
)
console.log('um')
const potentialUser = res?.data
console.log('res', res)
console.log('data ', res?.data)
console.log('good2')

if (!potentialUser) {
console.info(
Expand Down
6 changes: 3 additions & 3 deletions pages/api/process/topics.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { NextApiRequest, NextApiResponse } from 'next'
import axios from 'axios'
import topics from '@/data/topics'
import Topic from '@/db/models/Topic'
import { TopicModel } from '@/db/models'
import dbConnect from '@/db/dbConnect'

const getTopicImage = async (topic: string) => {
Expand All @@ -28,9 +28,9 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
let count = 0
for (const topicName of topics) {
if (count < size) {
const exists = await Topic.findOne({ name: topicName })
const exists = await TopicModel.findOne({ name: topicName })
if (!exists) {
const newTopic = new Topic()
const newTopic = new TopicModel()
newTopic.name = topicName
newTopic.image = await getTopicImage(topicName)
await newTopic.save()
Expand Down
Empty file added pages/api/recording/index.ts
Empty file.
Empty file added pages/api/session/index.ts
Empty file.
6 changes: 3 additions & 3 deletions pages/api/topic.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { NextApiRequest, NextApiResponse } from 'next'
import dbConnect from '@/db/dbConnect'
import Topic from '@/db/models/Topic'
import { TopicModel } from '@/db/models'

export default async (req: NextApiRequest, res: NextApiResponse) => {
await dbConnect()

const count = await Topic.countDocuments().exec()
const count = await TopicModel.countDocuments().exec()
if (count === 0) {
return res.send('No Topics found')
}
const randomIndex = Math.floor(Math.random() * count)
const randomTopic = await Topic.findOne().skip(randomIndex).exec()
const randomTopic = await TopicModel.findOne().skip(randomIndex).exec()
res.json({ topic: randomTopic })
}
6 changes: 3 additions & 3 deletions pages/api/topics.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NextApiRequest, NextApiResponse } from 'next'
import dbConnect from '@/db/dbConnect'
import Topic from '@/db/models/Topic'
import { TopicModel } from '@/db/models'
import axios from 'axios'

export default async (req: NextApiRequest, res: NextApiResponse) => {
Expand All @@ -12,7 +12,7 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
return res.status(400).json({ error: 'Name not found on Request Body' })
}

const existingTopic = await Topic.findOne({ name })
const existingTopic = await TopicModel.findOne({ name })
if (existingTopic) {
return res.status(409).json({ error: 'Topic already exists', existingTopic })
}
Expand All @@ -21,7 +21,7 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
const imgResponse = await axios.get(unsplashURL)
const imageURL = imgResponse?.data?.results[0].urls?.regular

const newTopic = new Topic({ name: name, image: imageURL })
const newTopic = new TopicModel({ name: name, image: imageURL })

await newTopic.save()
console.log('created new topic', { topic: newTopic })
Expand Down
10 changes: 5 additions & 5 deletions pages/api/users/[userId].ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { NextApiRequest, NextApiResponse } from 'next'
import dbConnect from '@/db/dbConnect'
const ObjectId = require('mongoose').Types.ObjectId
import User from '@/db/models/User'
import { UserModel } from '@/db/models'
import { handleUnexpectedError, throw404 } from '@/helpers/APIHelper'

export default async (req: NextApiRequest, res: NextApiResponse) => {
Expand All @@ -18,7 +18,7 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
/* UPDATE User */
if (req.method === 'PATCH' && id) {
try {
const user = await User.findById(id).exec()
const user = await UserModel.findById(id).exec()
if (!user) return throw404(res, `player with ID ${id} does not exist`)
if (user) {
const updatedKeys: string[] = []
Expand All @@ -27,12 +27,12 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
/* updating settings */
if (key === 'settings') {
if (value?.defaultTimer) {
console.log('setting timer')
user[key].defaultTimer = value?.defaultTimer
updatedKeys.push(key)
}
if (value?.autofillSessionName !== undefined) {
console.log('boole')
user[key].autofillSessionName = value?.autofillSessionName
updatedKeys.push(key)
}
} else {
/* default updating */
Expand All @@ -52,7 +52,7 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
/* GET User */
} else if (req?.method === 'GET' && id) {
try {
const user = await User.findById(id)
const user = await UserModel.findById(id)
if (!user) {
return throw404(res, `Player with Id ${id} not found`)
}
Expand Down
23 changes: 16 additions & 7 deletions pages/api/users/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NextApiRequest, NextApiResponse } from 'next'
import dbConnect from '@/db/dbConnect'
import User from '@/db/models/User'
import { UserModel } from '@/db/models'
import { throw404 } from '@/helpers/APIHelper'

export default async (req: NextApiRequest, res: NextApiResponse) => {
Expand All @@ -21,10 +21,10 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
}
}

const existingPlayer = await User.exists({ username: username, email: email })
const existingPlayer = await UserModel.exists({ username: username, email: email })
if (!existingPlayer) {
try {
const player: any = new User({
const player: any = new UserModel({
username: username,
email: email,
provider: provider,
Expand All @@ -42,17 +42,26 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
return existingPlayer
}
} else if (req?.method === 'GET') {
if (req?.query?.username) {
console.log('name found')
const user = await User.findOne({ username: req?.query?.username })
if (req?.query?.username && req?.query?.providerId) {
console.log('name and providerId')
const user = await UserModel.findOne({
username: req?.query?.username,
'provider.providerId': req?.query?.providerId,
})
if (!user) {
return throw404(res, `Player ${req?.query?.username} Does not have an account`)
}
return res.json(user)
} else if (req?.query?.username) {
const user = await UserModel.findOne({ username: req?.query?.username })
if (!user) {
return throw404(res, `Player ${req?.query?.username} Does not have an account`)
}
console.log('returning single player')
res.setHeader('Content-Type', 'application/json')
return res.json(user)
}
const users = await User.find({}).limit(10).lean()
const users = await UserModel.find({}).limit(10).lean()
return res.json(users)
} else {
console.error('Method not Allowed')
Expand Down