Skip to content

Commit

Permalink
Refactor to dbTyped.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
Yasamato committed Dec 30, 2023
1 parent 6b20189 commit 27c8dfb
Show file tree
Hide file tree
Showing 13 changed files with 192 additions and 44 deletions.
32 changes: 6 additions & 26 deletions lib/db/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@
import Redis from 'ioredis'
import * as process from 'process'
import { Types } from '../../types/Components'
import { findOne, getAll } from './db'

import { getUser, getUsers } from './users'
import { getItem } from './items'
import { singularToPlural } from '../utils'
import { findOneTyped, getAllTyped } from './dbTyped'

const uri =
'CACHE_URL' in process.env ? process.env.CACHE_URL : 'redis://localhost'
Expand All @@ -21,13 +18,7 @@ export async function getSingleCache(
): Promise<string | object> {
let data = await getCache(type + '-' + _id)
if (data === null) {
if (type === Types.user) {
data = await getUser(_id)
} else if (type === Types.item) {
data = await getItem(_id)
} else {
data = await findOne(singularToPlural(type), { _id: _id })
}
data = await findOneTyped(type, _id)

if (data === null) {
return null
Expand All @@ -49,11 +40,7 @@ export async function updateSingleCache(
data?: string | object
) {
if (typeof data === 'undefined') {
if (type === Types.user) {
data = await getUser(_id)
} else {
data = await findOne(singularToPlural(type), { _id: _id })
}
data = await findOneTyped(type, _id)
}

await setCache(type + '-' + _id, data)
Expand All @@ -67,11 +54,8 @@ export async function getAllCache(type: Types): Promise<object[]> {

let data = await getCache(plural)
if (data === null) {
if (type === Types.user) {
data = await getUsers()
} else {
data = await getAll(plural)
}
data = await getAllTyped(type)

if (data === null) {
return []
}
Expand All @@ -87,11 +71,7 @@ export async function getAllCache(type: Types): Promise<object[]> {
*/
export async function updateAllCache(type: Types, data?: string | object) {
if (typeof data === 'undefined') {
if (type === Types.user) {
data = await getUsers()
} else {
data = await getAll(singularToPlural(type))
}
data = await getAllTyped(type)
}

await setCache(singularToPlural(type), data)
Expand Down
155 changes: 155 additions & 0 deletions lib/db/dbTyped.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import { Types } from '../../types/Components'
import { count, deleteOne, find, findOne, getAll, insert, updateOne } from './db'
import type { User, UserUpdate } from '../../types/User'
import type { List } from '../../types/List'
import type { Library } from '../../types/Library'
import type { Item } from '../../types/Item'
import type { Column } from '../../types/Column'
import type { Collection } from '../../types/Collection'
import { gatherUserInfo } from './users'
import { getSingleCache } from './cache'
import { getLastViews } from './views'

export async function getAllTyped(type: Types) {
switch (type) {
case Types.collection:
return (await getAll('collections')) as Collection[]
case Types.column:
return (await getAll('columns')) as Column[]
case Types.item:
return (await getAll('items')) as Item[]
case Types.library:
return (await getAll('libraries')) as Library[]
case Types.list:
return (await getAll('lists')) as List[]
case Types.user:
const users = (await getAll('users')) as User[]
return await Promise.all(
users.map(
async ({ uid }) => (await getSingleCache(Types.user, uid)) as User
)
)
}
}

export async function findTyped(type: Types, query: Record<string, any>) {
switch (type) {
case Types.collection:
return (await find('collections', query)) as Collection[]
case Types.column:
return (await find('columns', query)) as Column[]
case Types.item:
return (await find('items', query)) as Item[]
case Types.library:
return (await find('libraries', query)) as Library[]
case Types.list:
return (await find('lists', query)) as List[]
case Types.user:
return (await find('users', query)) as User[]
}
}

export async function findOneTyped(type: Types, _id: string | Record<string, any>) {
switch (type) {
case Types.collection:
return (await findOne('collections', typeof _id === 'string' ? { _id } : _id)) as Collection | null
case Types.column:
return (await findOne('columns', typeof _id === 'string' ? { _id } : _id)) as Column | null
case Types.item:
const item = (await findOne('items', typeof _id === 'string' ? { _id } : _id)) as Item | null
if (item !== null) {
item.stars = await countTyped(Types.user, { favs: [_id] })
item.views = 0 // await count(Types.item, 1000)
}
return item
case Types.library:
return (await findOne('libraries', typeof _id === 'string' ? { _id } : _id)) as Library | null
case Types.list:
return (await findOne('lists', typeof _id === 'string' ? { _id } : _id)) as List | null
case Types.user:
const user = (await findOne('users', typeof _id === 'string' ? { uid: _id } : _id)) as User | null
return await gatherUserInfo(user)
}
}

export async function countTyped(type: Types, query?: Record<string, any>) {
switch (type) {
case Types.collection:
return await count('collections', query)
case Types.column:
return await count('columns', query)
case Types.item:
return await count('items', query)
case Types.library:
return await count('libraries', query)
case Types.list:
return await count('lists', query)
case Types.user:
return await count('users', query)
}
}

export async function getByUrlIdTyped(
type: Types,
urlId: string
) {
return findOneTyped(type, {urlId})
}

export async function insertTyped(
type: Types,
data: UserUpdate | Record<string, any>
) {
switch (type) {
case Types.collection:
return await insert('collections', data)
case Types.column:
return await insert('columns', data)
case Types.item:
return await insert('items', data)
case Types.library:
return await insert('libraries', data)
case Types.list:
return await insert('lists', data)
case Types.user:
if (instanceof data UserUpdate)
return await insert('users', data)
}
}

export async function updateOneTyped(type: Types, _id: string | Record<string, any>, data) {
switch (type) {
case Types.collection:
return await updateOne('collections', typeof _id === 'string' ? { _id } : _id, data)
case Types.column:
return await updateOne('columns', typeof _id === 'string' ? { _id } : _id, data)
case Types.item:
return await updateOne('items', typeof _id === 'string' ? { _id } : _id, data)
case Types.library:
return await updateOne('libraries', typeof _id === 'string' ? { _id } : _id, data)
case Types.list:
return await updateOne('lists', typeof _id === 'string' ? { _id } : _id, data)
case Types.user:
return await updateOne('users', typeof _id === 'string' ? { uid: _id } : _id, data)
}
}

export async function deleteOneTyped(
type: Types,
query: Record<string, any>
) {
switch (type) {
case Types.collection:
return await deleteOne('collections', query)
case Types.column:
return await deleteOne('columns', query)
case Types.item:
return await deleteOne('items', query)
case Types.library:
return await deleteOne('libraries', query)
case Types.list:
return await deleteOne('lists', query)
case Types.user:
return await deleteOne('users', query)
}
}
9 changes: 5 additions & 4 deletions lib/db/lists.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { deleteOne, find, findOne, getAll, insert, updateOne } from './db'
import { clearSingleCache, updateAllCache, updateSingleCache } from './cache'
import { Types } from '../../types/Components'
import { getUser, updateUser } from './users'
import { List, ListUpdate } from '../../types/List'
import { User } from '../../types/User'
import { updateUser } from './users'
import type { List, ListUpdate } from '../../types/List'
import type { User } from '../../types/User'
import { findOneTyped } from './dbTyped'

export async function getLists(): Promise<List[]> {
return (await getAll('lists')) as List[]
Expand Down Expand Up @@ -69,7 +70,7 @@ export async function updateList(
export async function deleteList(_id: string) {
// remove list entry from owner
const list = await getList(_id)
const owner = await getUser(list.owner)
const owner = await findOneTyped(Types.user, list.owner) as User
owner.lists = owner.lists.filter((userList) => userList !== _id)

await updateUser(owner.uid, {
Expand Down
8 changes: 5 additions & 3 deletions pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import NextAuth from 'next-auth'
import DiscordProvider from 'next-auth/providers/discord'
import { addUser, getUser } from '../../../lib/db/users'
import { AccountType } from '../../../types/User'
import { addUser } from '../../../lib/db/users'
import { AccountType, type User } from '../../../types/User'
import { MongoDBAdapter } from '@next-auth/mongodb-adapter'
import { dbClient } from '../../../lib/db/db'
import { ObjectId } from 'mongodb'
import type { AuthOptions } from 'next-auth'
import { findOneTyped } from '../../../lib/db/dbTyped'
import { Types } from '../../../types/Components'

export const authOptions: AuthOptions = {
providers: [
Expand All @@ -26,7 +28,7 @@ export const authOptions: AuthOptions = {
const id = user.id.toString()
session.user.uid = id

const userData = await getUser(id)
const userData = await findOneTyped(Types.user, id) as User
// create user account if not found
if (userData === null) {
console.log(
Expand Down
6 changes: 4 additions & 2 deletions pages/api/edit/user.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { authOptions } from '../auth/[...nextauth]'
import { getServerSession } from 'next-auth/next'
import { isAdmin, isCurrentUser } from '../../../lib/session'
import { getUser, updateUser } from '../../../lib/db/users'
import { updateUser } from '../../../lib/db/users'
import { updateAllCache, updateSingleCache } from '../../../lib/db/cache'
import { Types } from '../../../types/Components'
import { NextApiRequest, NextApiResponse } from 'next'
import { findOneTyped } from '../../../lib/db/dbTyped'
import type { User } from '../../../types/User'

export default async function apiEditUser(
req: NextApiRequest,
Expand All @@ -18,7 +20,7 @@ export default async function apiEditUser(
delete d.accountType
}
// @ts-ignore
const oldUser = await getUser(d.uid === 'me' ? session.user.uid : d.uid)
const oldUser = await findOneTyped(Types.user, d.uid === 'me' ? session.user.uid : d.uid) as User

// @ts-ignore
await updateUser(d.uid === 'me' ? session.user.uid : d.uid, d)
Expand Down
5 changes: 3 additions & 2 deletions pages/edit/user/[id].tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import Head from 'next/head'
import { useSession } from 'next-auth/react'
import Link from 'next/link'
import { getUser } from '../../../lib/db/users'
import { isAdmin, isCurrentUser } from '../../../lib/session'
import EditUser from '../../../components/edit/EditUser'
import NotAdmin from '../../../components/layout/NotAdmin'
import ViewAllButton from '../../../components/buttons/ViewAllButton'
import { Types } from '../../../types/Components'
import { findOneTyped } from '../../../lib/db/dbTyped'
import type { User } from '../../../types/User'

export default function EditorUser({ uid, user }) {
const { data: session } = useSession()
Expand Down Expand Up @@ -56,7 +57,7 @@ export default function EditorUser({ uid, user }) {
EditorUser.auth = {}

export async function getServerSideProps({ params }) {
const user = await getUser(params.id)
const user = await findOneTyped(Types.user, params.id) as User
if (!user) {
return {
notFound: true,
Expand Down
12 changes: 6 additions & 6 deletions pages/user/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@ import { useSession } from 'next-auth/react'
import { isAdmin, isCurrentUser } from '../../lib/session'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import DataBadge from '../../components/data/DataBadge'
import { getUser } from '../../lib/db/users'
import ListBoard from '../../components/boards/ListBoard'
import ItemBoard from '../../components/boards/ItemBoard'
import Meta from '../../components/layout/Meta'
import React, { FC } from 'react'
import useSWR from 'swr'
import { getAllCache } from '../../lib/db/cache'
import { Types } from '../../types/Components'
import { User } from '../../types/User'
import { List } from '../../types/List'
import { Item } from '../../types/Item'
import { Column } from '../../types/Column'
import type { User } from '../../types/User'
import type { List } from '../../types/List'
import type { Item } from '../../types/Item'
import type { Column } from '../../types/Column'
import { faCog } from '@fortawesome/free-solid-svg-icons/faCog'
import AccountTypeBadge from '../../components/badge/AccountTypeBadge'
import { findOneTyped } from '../../lib/db/dbTyped'

type Props = {
user: User
Expand Down Expand Up @@ -217,7 +217,7 @@ const User: FC<Props> = ({ user, lists, items, columns }) => {
export default User

export async function getServerSideProps({ params }) {
const user = await getUser(params.id)
const user = await findOneTyped(Types.user, params.id) as User

if (!user) {
return {
Expand Down
1 change: 1 addition & 0 deletions types/Collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export interface Collection {
description: string
columns: string[]
items: string[]
views: number
}

export interface CollectionUpdate {
Expand Down
1 change: 1 addition & 0 deletions types/Column.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export interface Column {
description: string
type: ColumnType
values: string[]
views: number
}

export enum ColumnType {
Expand Down
1 change: 1 addition & 0 deletions types/Item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export interface Item {
description: string
data: Record<string, boolean | string | string[]>
stars: number
views: number
}

export interface ItemUpdate {
Expand Down
1 change: 1 addition & 0 deletions types/Library.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export interface Library {
description: string
collections: string[]
order: number
views: number
}

export interface LibraryWithCollection {
Expand Down
1 change: 1 addition & 0 deletions types/List.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export interface List {
description: string
items: string[]
columns: string[]
views: number
}

export interface ListUpdate {
Expand Down
Loading

0 comments on commit 27c8dfb

Please sign in to comment.