-
- {t('modals.login.title')}
-
-
-
-
-
-
+
+
+
+
+
{t('modals.login.title')}
+
+
+
+
-
-
-
-
-
+
+
+
+
)
}
diff --git a/components/Party/index.tsx b/components/Party/index.tsx
index 6fcc15b9..3f0e1fc7 100644
--- a/components/Party/index.tsx
+++ b/components/Party/index.tsx
@@ -25,18 +25,6 @@ interface Props {
}
const Party = (props: Props) => {
- // Cookies
- const cookie = getCookie('account')
- const accountData: AccountCookie = cookie
- ? JSON.parse(cookie as string)
- : null
-
- const headers = useMemo(() => {
- return accountData
- ? { headers: { Authorization: `Bearer ${accountData.token}` } }
- : {}
- }, [accountData])
-
// Set up router
const router = useRouter()
@@ -55,12 +43,13 @@ const Party = (props: Props) => {
async function createParty(extra: boolean = false) {
let body = {
party: {
- ...(accountData && { user_id: accountData.userId }),
extra: extra,
},
}
- return await api.endpoints.parties.create(body, headers)
+ console.log(body)
+
+ return await api.endpoints.parties.create(body)
}
// Methods: Updating the party's details
@@ -68,13 +57,9 @@ const Party = (props: Props) => {
appState.party.extra = event.target.checked
if (party.id) {
- api.endpoints.parties.update(
- party.id,
- {
- party: { extra: event.target.checked },
- },
- headers
- )
+ api.endpoints.parties.update(party.id, {
+ party: { extra: event.target.checked },
+ })
}
}
@@ -86,17 +71,13 @@ const Party = (props: Props) => {
) {
if (appState.party.id)
api.endpoints.parties
- .update(
- appState.party.id,
- {
- party: {
- name: name,
- description: description,
- raid_id: raid?.id,
- },
+ .update(appState.party.id, {
+ party: {
+ name: name,
+ description: description,
+ raid_id: raid?.id,
},
- headers
- )
+ })
.then(() => {
appState.party.name = name
appState.party.description = description
@@ -110,7 +91,7 @@ const Party = (props: Props) => {
function deleteTeam(event: React.MouseEvent
) {
if (appState.party.editable && appState.party.id) {
api.endpoints.parties
- .destroy({ id: appState.party.id, params: headers })
+ .destroy({ id: appState.party.id })
.then(() => {
// Push to route
router.push('/')
@@ -131,26 +112,28 @@ const Party = (props: Props) => {
}
// Methods: Storing party data
- const storeParty = function (party: Party) {
+ const storeParty = function (team: Party) {
// Store the important party and state-keeping values
- appState.party.name = party.name
- appState.party.description = party.description
- appState.party.raid = party.raid
- appState.party.updated_at = party.updated_at
- appState.party.job = party.job
- appState.party.jobSkills = party.job_skills
+ appState.party.name = team.name
+ appState.party.description = team.description
+ appState.party.raid = team.raid
+ appState.party.updated_at = team.updated_at
+ appState.party.job = team.job
+ appState.party.jobSkills = team.job_skills
- appState.party.id = party.id
- appState.party.extra = party.extra
- appState.party.user = party.user
- appState.party.favorited = party.favorited
- appState.party.created_at = party.created_at
- appState.party.updated_at = party.updated_at
+ appState.party.id = team.id
+ appState.party.extra = team.extra
+ appState.party.user = team.user
+ appState.party.favorited = team.favorited
+ appState.party.created_at = team.created_at
+ appState.party.updated_at = team.updated_at
+
+ appState.party.detailsVisible = false
// Populate state
- storeCharacters(party.characters)
- storeWeapons(party.weapons)
- storeSummons(party.summons)
+ storeCharacters(team.characters)
+ storeWeapons(team.weapons)
+ storeSummons(team.summons)
}
const storeCharacters = (list: Array) => {
@@ -256,13 +239,11 @@ const Party = (props: Props) => {
{navigation}
- {
-
- }
+
)
}
diff --git a/components/PartyDetails/index.tsx b/components/PartyDetails/index.tsx
index 59ff9714..a171ad48 100644
--- a/components/PartyDetails/index.tsx
+++ b/components/PartyDetails/index.tsx
@@ -1,5 +1,4 @@
import React, { useState } from 'react'
-import Head from 'next/head'
import { useRouter } from 'next/router'
import { useSnapshot } from 'valtio'
import { useTranslation } from 'next-i18next'
@@ -14,7 +13,6 @@ import CharLimitedFieldset from '~components/CharLimitedFieldset'
import RaidDropdown from '~components/RaidDropdown'
import TextFieldset from '~components/TextFieldset'
-import { accountState } from '~utils/accountState'
import { appState } from '~utils/appState'
import CheckIcon from '~public/icons/Check.svg'
@@ -25,18 +23,6 @@ import './index.scss'
import Link from 'next/link'
import { formatTimeAgo } from '~utils/timeAgo'
-const emptyRaid: Raid = {
- id: '',
- name: {
- en: '',
- ja: '',
- },
- slug: '',
- level: 0,
- group: 0,
- element: 0,
-}
-
// Props
interface Props {
editable: boolean
@@ -48,7 +34,6 @@ interface Props {
const PartyDetails = (props: Props) => {
const { party, raids } = useSnapshot(appState)
- const { account } = useSnapshot(accountState)
const { t } = useTranslation('common')
const router = useRouter()
@@ -56,7 +41,8 @@ const PartyDetails = (props: Props) => {
const nameInput = React.createRef()
const descriptionInput = React.createRef()
- const raidSelect = React.createRef()
+
+ const [raidSlug, setRaidSlug] = useState('')
const readOnlyClasses = classNames({
PartyDetails: true,
@@ -116,10 +102,14 @@ const PartyDetails = (props: Props) => {
appState.party.detailsVisible = !appState.party.detailsVisible
}
+ function receiveRaid(slug?: string) {
+ if (slug) setRaidSlug(slug)
+ }
+
function updateDetails(event: React.MouseEvent) {
const nameValue = nameInput.current?.value
const descriptionValue = descriptionInput.current?.value
- const raid = raids.find((raid) => raid.slug === raidSelect.current?.value)
+ const raid = raids.find((raid) => raid.slug === raidSlug)
props.updateCallback(nameValue, descriptionValue, raid)
toggleDetails()
@@ -129,11 +119,11 @@ const PartyDetails = (props: Props) => {
if (party.user)
return (
)
else return
@@ -220,8 +210,8 @@ const PartyDetails = (props: Props) => {
/>
) => void
}
+// Set up empty raid for "All raids"
+const allRaidsOption = {
+ id: '0',
+ name: {
+ en: 'All raids',
+ ja: '全て',
+ },
+ slug: 'all',
+ level: 0,
+ group: 0,
+ element: 0,
+}
+
const RaidDropdown = React.forwardRef(
function useFieldSet(props, ref) {
// Set up router for locale
@@ -28,7 +42,7 @@ const RaidDropdown = React.forwardRef(
// Set up local states for storing raids
const [open, setOpen] = useState(false)
- const [currentRaid, setCurrentRaid] = useState()
+ const [currentRaid, setCurrentRaid] = useState(undefined)
const [raids, setRaids] = useState()
const [sortedRaids, setSortedRaids] = useState()
@@ -37,38 +51,17 @@ const RaidDropdown = React.forwardRef(
}
// Organize raids into groups on mount
- const organizeRaids = useCallback(
+ const organizeAllRaids = useCallback(
(raids: Raid[]) => {
- // Set up empty raid for "All raids"
- const all = {
- id: '0',
- name: {
- en: 'All raids',
- ja: '全て',
- },
- slug: 'all',
- level: 0,
- group: 0,
- element: 0,
- }
-
- const numGroups = Math.max.apply(
- Math,
- raids.map((raid) => raid.group)
- )
- let groupedRaids = []
-
- for (let i = 0; i <= numGroups; i++) {
- groupedRaids[i] = raids.filter((raid) => raid.group == i)
- }
+ let { sortedRaids } = organizeRaids(raids)
if (props.showAllRaidsOption) {
- raids.unshift(all)
- groupedRaids[0].unshift(all)
+ raids.unshift(allRaidsOption)
+ sortedRaids[0].unshift(allRaidsOption)
}
setRaids(raids)
- setSortedRaids(groupedRaids)
+ setSortedRaids(sortedRaids)
appState.raids = raids
},
[props.showAllRaidsOption]
@@ -78,22 +71,19 @@ const RaidDropdown = React.forwardRef(
useEffect(() => {
api.endpoints.raids
.getAll()
- .then((response) =>
- organizeRaids(response.data.map((r: any) => r.raid))
- )
+ .then((response) => organizeAllRaids(response.data))
}, [organizeRaids])
// Set current raid on mount
useEffect(() => {
if (raids && props.currentRaid) {
const raid = raids.find((raid) => raid.slug === props.currentRaid)
- setCurrentRaid(raid)
+ if (raid) setCurrentRaid(raid)
}
}, [raids, props.currentRaid])
// Enable changing select value
function handleChange(value: string) {
- console.log(value)
if (props.onChange) props.onChange(value)
if (raids) {
@@ -110,13 +100,12 @@ const RaidDropdown = React.forwardRef(
sortedRaids[index].length > 0 &&
sortedRaids[index]
.sort((a, b) => a.element - b.element)
- .map((item, i) => {
- return (
-
- {item.name[locale]}
-
- )
- })
+ .map((item, i) => (
+
+ {item.name[locale]}
+
+ ))
+
return (
(
}
return (
-
+
+
+
)
}
)
diff --git a/components/SearchModal/index.tsx b/components/SearchModal/index.tsx
index 61b0e24a..9b5912de 100644
--- a/components/SearchModal/index.tsx
+++ b/components/SearchModal/index.tsx
@@ -85,11 +85,11 @@ const SearchModal = (props: Props) => {
page: currentPage,
})
.then((response) => {
- setTotalPages(response.data.total_pages)
- setRecordCount(response.data.count)
+ setTotalPages(response.data.meta.total_pages)
+ setRecordCount(response.data.meta.count)
if (replace) {
- replaceResults(response.data.count, response.data.results)
+ replaceResults(response.data.meta.count, response.data.results)
} else {
appendResults(response.data.results)
}
@@ -330,7 +330,7 @@ const SearchModal = (props: Props) => {
,
+ HTMLSelectElement
+ > {
open: boolean
- defaultValue?: string | number
- placeholder?: string
- name?: string
+ trigger?: React.ReactNode
children?: React.ReactNode
onClick?: () => void
- onChange?: (value: string) => void
+ onValueChange?: (value: string) => void
triggerClass?: string
}
-const Select = React.forwardRef
(function useFieldSet(
- props,
- ref
-) {
+const Select = (props: Props) => {
+ const [value, setValue] = useState('')
+
+ useEffect(() => {
+ if (props.value && props.value !== '') setValue(`${props.value}`)
+ else setValue('')
+ }, [props.value])
+
+ function onValueChange(newValue: string) {
+ setValue(`${newValue}`)
+ if (props.onValueChange) props.onValueChange(newValue)
+ }
+
+ console.log(value)
return (
@@ -52,6 +62,6 @@ const Select = React.forwardRef(function useFieldSet(
)
-})
+}
export default Select
diff --git a/components/SignupModal/index.tsx b/components/SignupModal/index.tsx
index 0610ed49..44d29b59 100644
--- a/components/SignupModal/index.tsx
+++ b/components/SignupModal/index.tsx
@@ -5,13 +5,17 @@ import { useRouter } from 'next/router'
import { Trans, useTranslation } from 'next-i18next'
import { AxiosResponse } from 'axios'
-import * as Dialog from '@radix-ui/react-dialog'
-
import api from '~utils/api'
import { accountState } from '~utils/accountState'
import Button from '~components/Button'
import Input from '~components/Input'
+import {
+ Dialog,
+ DialogTrigger,
+ DialogContent,
+ DialogClose,
+} from '~components/Dialog'
import CrossIcon from '~public/icons/Cross.svg'
import './index.scss'
@@ -75,19 +79,19 @@ const SignupModal = (props: Props) => {
.create(body)
.then((response) => {
storeCookieInfo(response)
- return response.data.user.user_id
+ return response.data.id
})
.then((id) => fetchUserInfo(id))
.then((infoResponse) => storeUserInfo(infoResponse))
}
function storeCookieInfo(response: AxiosResponse) {
- const user = response.data.user
+ const resp = response.data
const cookieObj: AccountCookie = {
- userId: user.user_id,
- username: user.username,
- token: user.token,
+ userId: resp.id,
+ username: resp.username,
+ token: resp.token,
}
setCookie('account', cookieObj, { path: '/' })
@@ -98,11 +102,11 @@ const SignupModal = (props: Props) => {
}
function storeUserInfo(response: AxiosResponse) {
- const user = response.data.user
+ const user = response.data
const cookieObj: UserCookie = {
- picture: user.picture.picture,
- element: user.picture.element,
+ picture: user.avatar.picture,
+ element: user.avatar.element,
language: user.language,
gender: user.gender,
}
@@ -113,8 +117,8 @@ const SignupModal = (props: Props) => {
accountState.account.user = {
id: user.id,
username: user.username,
- picture: user.picture.picture,
- element: user.picture.element,
+ picture: user.avatar.picture,
+ element: user.avatar.element,
gender: user.gender,
}
@@ -251,73 +255,67 @@ const SignupModal = (props: Props) => {
}
return (
-
-
+
-
- event.preventDefault()}
- >
-
-
- {t('modals.signup.title')}
-
-
-
-
-
-
+
+
+
+
+
{t('modals.signup.title')}
+
+
+
+
-
-
-
-
-
+
+
+
+
)
}
diff --git a/components/SummonGrid/index.tsx b/components/SummonGrid/index.tsx
index ff6edf61..1720c032 100644
--- a/components/SummonGrid/index.tsx
+++ b/components/SummonGrid/index.tsx
@@ -96,13 +96,13 @@ const SummonGrid = (props: Props) => {
if (props.pushHistory) props.pushHistory(`/p/${party.shortcode}`)
saveSummon(party.id, summon, position).then((response) =>
- storeGridSummon(response.data.grid_summon)
+ storeGridSummon(response.data)
)
})
} else {
if (party.editable)
saveSummon(party.id, summon, position).then((response) =>
- storeGridSummon(response.data.grid_summon)
+ storeGridSummon(response.data)
)
}
}
diff --git a/components/SummonResult/index.scss b/components/SummonResult/index.scss
index 11b51c2d..69de7ce4 100644
--- a/components/SummonResult/index.scss
+++ b/components/SummonResult/index.scss
@@ -28,7 +28,7 @@
gap: $unit-half;
h5 {
- color: var(--text-secondary);
+ color: var(--text-tertiary);
display: inline-block;
font-size: $font-medium;
font-weight: $medium;
diff --git a/components/WeaponGrid/index.tsx b/components/WeaponGrid/index.tsx
index ab5bd933..ee296e71 100644
--- a/components/WeaponGrid/index.tsx
+++ b/components/WeaponGrid/index.tsx
@@ -86,12 +86,12 @@ const WeaponGrid = (props: Props) => {
if (props.pushHistory) props.pushHistory(`/p/${party.shortcode}`)
saveWeapon(party.id, weapon, position).then((response) =>
- storeGridWeapon(response.data.grid_weapon)
+ storeGridWeapon(response.data)
)
})
} else {
saveWeapon(party.id, weapon, position).then((response) =>
- storeGridWeapon(response.data.grid_weapon)
+ storeGridWeapon(response.data)
)
}
}
diff --git a/components/WeaponResult/index.scss b/components/WeaponResult/index.scss
index 43017a54..c67efcc9 100644
--- a/components/WeaponResult/index.scss
+++ b/components/WeaponResult/index.scss
@@ -28,7 +28,7 @@
gap: $unit-half;
h5 {
- color: var(--text-secondary);
+ color: var(--text-tertiary);
display: inline-block;
font-size: $font-medium;
font-weight: $medium;
diff --git a/pages/[username].tsx b/pages/[username].tsx
index d941828a..0767c736 100644
--- a/pages/[username].tsx
+++ b/pages/[username].tsx
@@ -1,7 +1,6 @@
import React, { useCallback, useEffect, useState } from 'react'
import Head from 'next/head'
-import { getCookie } from 'cookies-next'
import { queryTypes, useQueryState } from 'next-usequerystate'
import { useRouter } from 'next/router'
import { useTranslation } from 'next-i18next'
@@ -10,32 +9,29 @@ import InfiniteScroll from 'react-infinite-scroll-component'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import api from '~utils/api'
+import setUserToken from '~utils/setUserToken'
+import extractFilters from '~utils/extractFilters'
+import organizeRaids from '~utils/organizeRaids'
import useDidMountEffect from '~utils/useDidMountEffect'
import { elements, allElement } from '~utils/Element'
+import { emptyPaginationObject } from '~utils/emptyStates'
import GridRep from '~components/GridRep'
import GridRepCollection from '~components/GridRepCollection'
import FilterBar from '~components/FilterBar'
import type { NextApiRequest, NextApiResponse } from 'next'
+import type { FilterObject, PaginationObject } from '~types'
interface Props {
user?: User
- teams?: { count: number; total_pages: number; results: Party[] }
+ teams?: Party[]
+ meta: PaginationObject
raids: Raid[]
sortedRaids: Raid[][]
}
const ProfileRoute: React.FC
= (props: Props) => {
- // Set up cookies
- const cookie = getCookie('account')
- const accountData: AccountCookie = cookie
- ? JSON.parse(cookie as string)
- : null
- const headers = accountData
- ? { Authorization: `Bearer ${accountData.token}` }
- : {}
-
// Set up router
const router = useRouter()
const { username } = router.query
@@ -61,16 +57,20 @@ const ProfileRoute: React.FC = (props: Props) => {
// Recency is in seconds
const [element, setElement] = useQueryState('element', {
defaultValue: -1,
+ history: 'push',
parse: (query: string) => parseElement(query),
serialize: (value) => serializeElement(value),
})
const [raidSlug, setRaidSlug] = useQueryState('raid', {
defaultValue: 'all',
+ history: 'push',
+ })
+ const [recency, setRecency] = useQueryState('recency', {
+ defaultValue: -1,
+ history: 'push',
+ parse: (query: string) => parseInt(query),
+ serialize: (value) => `${value}`,
})
- const [recency, setRecency] = useQueryState(
- 'recency',
- queryTypes.integer.withDefault(-1)
- )
// Define transformers for element
function parseElement(query: string) {
@@ -95,9 +95,9 @@ const ProfileRoute: React.FC = (props: Props) => {
// Set the initial parties from props
useEffect(() => {
if (props.teams) {
- setTotalPages(props.teams.total_pages)
- setRecordCount(props.teams.count)
- replaceResults(props.teams.count, props.teams.results)
+ setTotalPages(props.meta.totalPages)
+ setRecordCount(props.meta.count)
+ replaceResults(props.meta.count, props.teams)
}
setCurrentPage(1)
}, [])
@@ -113,6 +113,7 @@ const ProfileRoute: React.FC = (props: Props) => {
if (error.response != null) {
console.error(error)
} else {
+ // TODO: Put an alert here
console.error('There was an error.')
}
}, [])
@@ -132,18 +133,17 @@ const ProfileRoute: React.FC = (props: Props) => {
api.endpoints.users
.getOne({
id: username,
- params: { ...filters, ...{ headers: headers } },
+ params: { ...filters },
})
.then((response) => {
- setTotalPages(response.data.parties.total_pages)
- setRecordCount(response.data.parties.count)
+ const results = response.data.profile.parties
+ const meta = response.data.meta
- if (replace)
- replaceResults(
- response.data.parties.count,
- response.data.parties.results
- )
- else appendResults(response.data.parties.results)
+ setTotalPages(meta.total_pages)
+ setRecordCount(meta.count)
+
+ if (replace) replaceResults(meta.count, results)
+ else appendResults(results)
})
.catch((error) => handleError(error))
}
@@ -166,12 +166,11 @@ const ProfileRoute: React.FC = (props: Props) => {
// Fetch all raids on mount, then find the raid in the URL if present
useEffect(() => {
api.endpoints.raids.getAll().then((response) => {
- const cleanRaids: Raid[] = response.data.map((r: any) => r.raid)
- setRaids(cleanRaids)
+ setRaids(response.data)
setRaidsLoading(false)
- const raid = cleanRaids.find((r) => r.slug === raidSlug)
+ const raid = response.data.find((r: Raid) => r.slug === raidSlug)
setRaid(raid)
return raid
@@ -202,16 +201,16 @@ const ProfileRoute: React.FC = (props: Props) => {
raidSlug?: string
recency?: number
}) {
- if (element == 0) setElement(0)
- else if (element) setElement(element)
+ if (element == 0) setElement(0, { shallow: true })
+ else if (element) setElement(element, { shallow: true })
if (raids && raidSlug) {
const raid = raids.find((raid) => raid.slug === raidSlug)
setRaid(raid)
- setRaidSlug(raidSlug)
+ setRaidSlug(raidSlug, { shallow: true })
}
- if (recency) setRecency(recency)
+ if (recency) setRecency(recency, { shallow: true })
}
// Methods: Navigation
@@ -283,11 +282,11 @@ const ProfileRoute: React.FC = (props: Props) => {
>
{props.user?.username}
@@ -331,103 +330,54 @@ export const getServerSidePaths = async () => {
// prettier-ignore
export const getServerSideProps = async ({ req, res, locale, query }: { req: NextApiRequest, res: NextApiResponse, locale: string, query: { [index: string]: string } }) => {
- // Cookies
- const cookie = getCookie("account", { req, res })
- const accountData: AccountCookie = cookie
- ? JSON.parse(cookie as string)
- : null
-
- const headers = accountData
- ? { headers: { Authorization: `Bearer ${accountData.token}` } }
- : {}
+ // Set headers for server-side requests
+ setUserToken(req, res)
+ // Fetch and organize raids
let { raids, sortedRaids } = await api.endpoints.raids
- .getAll({ params: headers })
- .then((response) => organizeRaids(response.data.map((r: any) => r.raid)))
-
- // Extract recency filter
- const recencyParam: number = parseInt(query.recency)
-
- // Extract element filter
- const elementParam: string = query.element
- const teamElement: TeamElement | undefined =
- elementParam === "all"
- ? allElement
- : elements.find(
- (element) => element.name.en.toLowerCase() === elementParam
- )
-
- // Extract raid filter
- const raidParam: string = query.raid
- const raid: Raid | undefined = raids.find((r) => r.slug === raidParam)
+ .getAll()
+ .then((response) => organizeRaids(response.data))
// Create filter object
- const filters: {
- raid?: string
- element?: number
- recency?: number
- } = {}
+ const filters: FilterObject = extractFilters(query, raids)
+ const params = {
+ params: { ...filters },
+ }
- if (recencyParam) filters.recency = recencyParam
- if (teamElement && teamElement.id > -1) filters.element = teamElement.id
- if (raid) filters.raid = raid.id
-
- // Fetch initial set of parties here
+ // Set up empty variables
let user: User | null = null
let teams: Party[] | null = null
+ let meta: PaginationObject = emptyPaginationObject
+
+ // Perform a request only if we received a username
if (query.username) {
const response = await api.endpoints.users.getOne({
id: query.username,
- params: {
- ...filters,
- },
- ...headers,
+ params,
})
- user = response.data.user
- teams = response.data.parties
+ // Assign values to pass to props
+ user = response.data.profile
+
+ if (response.data.profile.parties) teams = response.data.profile.parties
+ else teams = []
+
+ meta.count = response.data.meta.count
+ meta.totalPages = response.data.meta.total_pages
+ meta.perPage = response.data.meta.per_page
}
return {
props: {
user: user,
teams: teams,
+ meta: meta,
raids: raids,
sortedRaids: sortedRaids,
- ...(await serverSideTranslations(locale, ["common"])),
+ ...(await serverSideTranslations(locale, ['common'])),
// Will be passed to the page component as props
},
}
}
-const organizeRaids = (raids: Raid[]) => {
- // Set up empty raid for "All raids"
- const all = {
- id: '0',
- name: {
- en: 'All raids',
- ja: '全て',
- },
- slug: 'all',
- level: 0,
- group: 0,
- element: 0,
- }
-
- const numGroups = Math.max.apply(
- Math,
- raids.map((raid) => raid.group)
- )
- let groupedRaids = []
-
- for (let i = 0; i <= numGroups; i++) {
- groupedRaids[i] = raids.filter((raid) => raid.group == i)
- }
-
- return {
- raids: raids,
- sortedRaids: groupedRaids,
- }
-}
-
export default ProfileRoute
diff --git a/pages/_app.tsx b/pages/_app.tsx
index 1f403379..6d80149d 100644
--- a/pages/_app.tsx
+++ b/pages/_app.tsx
@@ -7,6 +7,7 @@ import type { AppProps } from 'next/app'
import Layout from '~components/Layout'
import { accountState } from '~utils/accountState'
+import setUserToken from '~utils/setUserToken'
import '../styles/globals.scss'
@@ -15,6 +16,8 @@ function MyApp({ Component, pageProps }: AppProps) {
const cookieData: AccountCookie = cookie ? JSON.parse(cookie as string) : null
useEffect(() => {
+ setUserToken()
+
if (cookie) {
console.log(`Logged in as user "${cookieData.username}"`)
diff --git a/pages/new/index.tsx b/pages/new/index.tsx
index ca77a77f..d1c48f0e 100644
--- a/pages/new/index.tsx
+++ b/pages/new/index.tsx
@@ -1,10 +1,11 @@
import React, { useEffect } from 'react'
-import { getCookie } from 'cookies-next'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import Party from '~components/Party'
import { appState } from '~utils/appState'
+import organizeRaids from '~utils/organizeRaids'
+import setUserToken from '~utils/setUserToken'
import api from '~utils/api'
import type { NextApiRequest, NextApiResponse } from 'next'
@@ -47,67 +48,33 @@ export const getServerSidePaths = async () => {
// prettier-ignore
export const getServerSideProps = async ({ req, res, locale, query }: { req: NextApiRequest, res: NextApiResponse, locale: string, query: { [index: string]: string } }) => {
- // Cookies
- const cookie = getCookie("account", { req, res })
- const accountData: AccountCookie = cookie
- ? JSON.parse(cookie as string)
- : null
-
- const headers = accountData
- ? { headers: { Authorization: `Bearer ${accountData.token}` } }
- : {}
+ // Set headers for server-side requests
+ setUserToken(req, res)
let { raids, sortedRaids } = await api.endpoints.raids
- .getAll({ params: headers })
- .then((response) => organizeRaids(response.data.map((r: any) => r.raid)))
-
+ .getAll()
+ .then((response) => organizeRaids(response.data))
+
let jobs = await api.endpoints.jobs
- .getAll({ params: headers })
- .then((response) => { return response.data })
-
- let jobSkills = await api.allSkills(headers)
- .then((response) => { return response.data })
-
+ .getAll()
+ .then((response) => {
+ return response.data
+ })
+
+ let jobSkills = await api.allJobSkills().then((response) => {
+ return response.data
+ })
+
return {
props: {
jobs: jobs,
jobSkills: jobSkills,
raids: raids,
sortedRaids: sortedRaids,
- ...(await serverSideTranslations(locale, ["common"])),
+ ...(await serverSideTranslations(locale, ['common'])),
// Will be passed to the page component as props
},
}
}
-const organizeRaids = (raids: Raid[]) => {
- // Set up empty raid for "All raids"
- const all = {
- id: '0',
- name: {
- en: 'All raids',
- ja: '全て',
- },
- slug: 'all',
- level: 0,
- group: 0,
- element: 0,
- }
-
- const numGroups = Math.max.apply(
- Math,
- raids.map((raid) => raid.group)
- )
- let groupedRaids = []
-
- for (let i = 0; i <= numGroups; i++) {
- groupedRaids[i] = raids.filter((raid) => raid.group == i)
- }
-
- return {
- raids: raids,
- sortedRaids: groupedRaids,
- }
-}
-
export default NewRoute
diff --git a/pages/p/[party].tsx b/pages/p/[party].tsx
index bc8715c1..0fca65ab 100644
--- a/pages/p/[party].tsx
+++ b/pages/p/[party].tsx
@@ -5,6 +5,7 @@ import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import Party from '~components/Party'
import { appState } from '~utils/appState'
+import organizeRaids from '~utils/organizeRaids'
import api from '~utils/api'
import type { NextApiRequest, NextApiResponse } from 'next'
@@ -55,7 +56,7 @@ export const getServerSideProps = async ({ req, res, locale, query }: { req: Nex
let { raids, sortedRaids } = await api.endpoints.raids
.getAll()
- .then((response) => organizeRaids(response.data.map((r: any) => r.raid)))
+ .then((response) => organizeRaids(response.data))
let jobs = await api.endpoints.jobs
.getAll({ params: headers })
@@ -63,9 +64,7 @@ export const getServerSideProps = async ({ req, res, locale, query }: { req: Nex
return response.data
})
- let jobSkills = await api.allSkills(headers).then((response) => {
- return response.data
- })
+ let jobSkills = await api.allJobSkills(headers).then((response) => response.data)
let party: Party | null = null
if (query.party) {
@@ -88,34 +87,4 @@ export const getServerSideProps = async ({ req, res, locale, query }: { req: Nex
}
}
-const organizeRaids = (raids: Raid[]) => {
- // Set up empty raid for "All raids"
- const all = {
- id: '0',
- name: {
- en: 'All raids',
- ja: '全て',
- },
- slug: 'all',
- level: 0,
- group: 0,
- element: 0,
- }
-
- const numGroups = Math.max.apply(
- Math,
- raids.map((raid) => raid.group)
- )
- let groupedRaids = []
-
- for (let i = 0; i <= numGroups; i++) {
- groupedRaids[i] = raids.filter((raid) => raid.group == i)
- }
-
- return {
- raids: raids,
- sortedRaids: groupedRaids,
- }
-}
-
export default PartyRoute
diff --git a/pages/saved.tsx b/pages/saved.tsx
index 6ec6417c..90fdc6ff 100644
--- a/pages/saved.tsx
+++ b/pages/saved.tsx
@@ -1,7 +1,6 @@
import React, { useCallback, useEffect, useState } from 'react'
import Head from 'next/head'
-import { getCookie } from 'cookies-next'
import { queryTypes, useQueryState } from 'next-usequerystate'
import { useRouter } from 'next/router'
import { useTranslation } from 'next-i18next'
@@ -11,31 +10,28 @@ import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import clonedeep from 'lodash.clonedeep'
import api from '~utils/api'
+import setUserToken from '~utils/setUserToken'
+import extractFilters from '~utils/extractFilters'
+import organizeRaids from '~utils/organizeRaids'
import useDidMountEffect from '~utils/useDidMountEffect'
import { elements, allElement } from '~utils/Element'
+import { emptyPaginationObject } from '~utils/emptyStates'
import GridRep from '~components/GridRep'
import GridRepCollection from '~components/GridRepCollection'
import FilterBar from '~components/FilterBar'
import type { NextApiRequest, NextApiResponse } from 'next'
+import type { FilterObject, PaginationObject } from '~types'
interface Props {
- teams?: { count: number; total_pages: number; results: Party[] }
+ teams?: Party[]
+ meta: PaginationObject
raids: Raid[]
sortedRaids: Raid[][]
}
const SavedRoute: React.FC = (props: Props) => {
- // Set up cookies
- const cookie = getCookie('account')
- const accountData: AccountCookie = cookie
- ? JSON.parse(cookie as string)
- : null
- const headers = accountData
- ? { Authorization: `Bearer ${accountData.token}` }
- : {}
-
// Set up router
const router = useRouter()
@@ -60,16 +56,20 @@ const SavedRoute: React.FC = (props: Props) => {
// Recency is in seconds
const [element, setElement] = useQueryState('element', {
defaultValue: -1,
+ history: 'push',
parse: (query: string) => parseElement(query),
serialize: (value) => serializeElement(value),
})
const [raidSlug, setRaidSlug] = useQueryState('raid', {
defaultValue: 'all',
+ history: 'push',
+ })
+ const [recency, setRecency] = useQueryState('recency', {
+ defaultValue: -1,
+ history: 'push',
+ parse: (query: string) => parseInt(query),
+ serialize: (value) => `${value}`,
})
- const [recency, setRecency] = useQueryState(
- 'recency',
- queryTypes.integer.withDefault(-1)
- )
// Define transformers for element
function parseElement(query: string) {
@@ -94,9 +94,9 @@ const SavedRoute: React.FC = (props: Props) => {
// Set the initial parties from props
useEffect(() => {
if (props.teams) {
- setTotalPages(props.teams.total_pages)
- setRecordCount(props.teams.count)
- replaceResults(props.teams.count, props.teams.results)
+ setTotalPages(props.meta.totalPages)
+ setRecordCount(props.meta.count)
+ replaceResults(props.meta.count, props.teams)
}
setCurrentPage(1)
}, [])
@@ -118,24 +118,36 @@ const SavedRoute: React.FC = (props: Props) => {
const fetchTeams = useCallback(
({ replace }: { replace: boolean }) => {
- const filters = {
+ const filters: {
+ [key: string]: any
+ } = {
+ element: element !== -1 ? element : undefined,
+ raid: raid ? raid.id : undefined,
+ recency: recency !== -1 ? recency : undefined,
+ page: currentPage,
+ }
+
+ Object.keys(filters).forEach(
+ (key) => filters[key] === undefined && delete filters[key]
+ )
+
+ const params = {
params: {
- element: element != -1 ? element : undefined,
- raid: raid ? raid.id : undefined,
- recency: recency != -1 ? recency : undefined,
- page: currentPage,
+ ...filters,
},
}
api
- .savedTeams({ ...filters, ...{ headers: headers } })
+ .savedTeams(params)
.then((response) => {
- setTotalPages(response.data.total_pages)
- setRecordCount(response.data.count)
+ const results = response.data.results
+ const meta = response.data.meta
- if (replace)
- replaceResults(response.data.count, response.data.results)
- else appendResults(response.data.results)
+ setTotalPages(meta.total_pages)
+ setRecordCount(meta.count)
+
+ if (replace) replaceResults(meta.count, results)
+ else appendResults(results)
})
.catch((error) => handleError(error))
},
@@ -157,12 +169,11 @@ const SavedRoute: React.FC = (props: Props) => {
// Fetch all raids on mount, then find the raid in the URL if present
useEffect(() => {
api.endpoints.raids.getAll().then((response) => {
- const cleanRaids: Raid[] = response.data.map((r: any) => r.raid)
- setRaids(cleanRaids)
+ setRaids(response.data)
setRaidsLoading(false)
- const raid = cleanRaids.find((r) => r.slug === raidSlug)
+ const raid = response.data.find((r: Raid) => r.slug === raidSlug)
setRaid(raid)
return raid
@@ -193,16 +204,16 @@ const SavedRoute: React.FC = (props: Props) => {
raidSlug?: string
recency?: number
}) {
- if (element == 0) setElement(0)
- else if (element) setElement(element)
+ if (element == 0) setElement(0, { shallow: true })
+ else if (element) setElement(element, { shallow: true })
if (raids && raidSlug) {
const raid = raids.find((raid) => raid.slug === raidSlug)
setRaid(raid)
- setRaidSlug(raidSlug)
+ setRaidSlug(raidSlug, { shallow: true })
}
- if (recency) setRecency(recency)
+ if (recency) setRecency(recency, { shallow: true })
}
// Methods: Favorites
@@ -212,7 +223,7 @@ const SavedRoute: React.FC = (props: Props) => {
}
function saveFavorite(teamId: string) {
- api.saveTeam({ id: teamId, params: headers }).then((response) => {
+ api.saveTeam({ id: teamId }).then((response) => {
if (response.status == 201) {
const index = parties.findIndex((p) => p.id === teamId)
const party = parties[index]
@@ -228,7 +239,7 @@ const SavedRoute: React.FC = (props: Props) => {
}
function unsaveFavorite(teamId: string) {
- api.unsaveTeam({ id: teamId, params: headers }).then((response) => {
+ api.unsaveTeam({ id: teamId }).then((response) => {
if (response.status == 200) {
const index = parties.findIndex((p) => p.id === teamId)
const party = parties[index]
@@ -336,94 +347,43 @@ export const getServerSidePaths = async () => {
// prettier-ignore
export const getServerSideProps = async ({ req, res, locale, query }: { req: NextApiRequest, res: NextApiResponse, locale: string, query: { [index: string]: string } }) => {
- // Cookies
- const cookie = getCookie("account", { req, res })
- const accountData: AccountCookie = cookie
- ? JSON.parse(cookie as string)
- : null
+ // Set headers for server-side requests
+ setUserToken(req, res)
- const headers = accountData
- ? { headers: { Authorization: `Bearer ${accountData.token}` } }
- : {}
-
+ // Fetch and organize raids
let { raids, sortedRaids } = await api.endpoints.raids
- .getAll({ params: headers })
- .then((response) => organizeRaids(response.data.map((r: any) => r.raid)))
-
- // Extract recency filter
- const recencyParam: number = parseInt(query.recency)
-
- // Extract element filter
- const elementParam: string = query.element
- const teamElement: TeamElement | undefined =
- elementParam === "all"
- ? allElement
- : elements.find(
- (element) => element.name.en.toLowerCase() === elementParam
- )
-
- // Extract raid filter
- const raidParam: string = query.raid
- const raid: Raid | undefined = raids.find((r) => r.slug === raidParam)
+ .getAll()
+ .then((response) => organizeRaids(response.data))
// Create filter object
- const filters: {
- raid?: string
- element?: number
- recency?: number
- } = {}
+ const filters: FilterObject = extractFilters(query, raids)
+ const params = {
+ params: { ...filters },
+ }
- if (recencyParam) filters.recency = recencyParam
- if (teamElement && teamElement.id > -1) filters.element = teamElement.id
- if (raid) filters.raid = raid.id
+ // Set up empty variables
+ let teams: Party[] | null = null
+ let meta: PaginationObject = emptyPaginationObject
- // Fetch initial set of parties here
- const response = await api.savedTeams({
- params: {
- ...filters,
- },
- ...headers
- })
+ // Fetch initial set of saved parties
+ const response = await api.savedTeams(params)
+
+ // Assign values to pass to props
+ teams = response.data.results
+ meta.count = response.data.meta.count
+ meta.totalPages = response.data.meta.total_pages
+ meta.perPage = response.data.meta.per_page
return {
props: {
- teams: response.data,
+ teams: teams,
+ meta: meta,
raids: raids,
sortedRaids: sortedRaids,
- ...(await serverSideTranslations(locale, ["common"])),
+ ...(await serverSideTranslations(locale, ['common'])),
// Will be passed to the page component as props
},
}
}
-const organizeRaids = (raids: Raid[]) => {
- // Set up empty raid for "All raids"
- const all = {
- id: '0',
- name: {
- en: 'All raids',
- ja: '全て',
- },
- slug: 'all',
- level: 0,
- group: 0,
- element: 0,
- }
-
- const numGroups = Math.max.apply(
- Math,
- raids.map((raid) => raid.group)
- )
- let groupedRaids = []
-
- for (let i = 0; i <= numGroups; i++) {
- groupedRaids[i] = raids.filter((raid) => raid.group == i)
- }
-
- return {
- raids: raids,
- sortedRaids: groupedRaids,
- }
-}
-
export default SavedRoute
diff --git a/pages/teams.tsx b/pages/teams.tsx
index fa03697c..5e6aca13 100644
--- a/pages/teams.tsx
+++ b/pages/teams.tsx
@@ -1,7 +1,6 @@
import React, { useCallback, useEffect, useState } from 'react'
import Head from 'next/head'
-import { getCookie } from 'cookies-next'
import { queryTypes, useQueryState } from 'next-usequerystate'
import { useRouter } from 'next/router'
import { useTranslation } from 'next-i18next'
@@ -11,31 +10,27 @@ import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import clonedeep from 'lodash.clonedeep'
import api from '~utils/api'
+import setUserToken from '~utils/setUserToken'
+import extractFilters from '~utils/extractFilters'
+import organizeRaids from '~utils/organizeRaids'
import useDidMountEffect from '~utils/useDidMountEffect'
import { elements, allElement } from '~utils/Element'
+import { emptyPaginationObject } from '~utils/emptyStates'
import GridRep from '~components/GridRep'
import GridRepCollection from '~components/GridRepCollection'
import FilterBar from '~components/FilterBar'
import type { NextApiRequest, NextApiResponse } from 'next'
+import type { FilterObject, PaginationObject } from '~types'
interface Props {
- teams?: { count: number; total_pages: number; results: Party[] }
- raids: Raid[]
+ teams?: Party[]
+ meta: PaginationObject
sortedRaids: Raid[][]
}
const TeamsRoute: React.FC = (props: Props) => {
- // Set up cookies
- const cookie = getCookie('account')
- const accountData: AccountCookie = cookie
- ? JSON.parse(cookie as string)
- : null
- const headers = accountData
- ? { Authorization: `Bearer ${accountData.token}` }
- : {}
-
// Set up router
const router = useRouter()
@@ -60,16 +55,20 @@ const TeamsRoute: React.FC = (props: Props) => {
// Recency is in seconds
const [element, setElement] = useQueryState('element', {
defaultValue: -1,
+ history: 'push',
parse: (query: string) => parseElement(query),
serialize: (value) => serializeElement(value),
})
const [raidSlug, setRaidSlug] = useQueryState('raid', {
defaultValue: 'all',
+ history: 'push',
+ })
+ const [recency, setRecency] = useQueryState('recency', {
+ defaultValue: -1,
+ history: 'push',
+ parse: (query: string) => parseInt(query),
+ serialize: (value) => `${value}`,
})
- const [recency, setRecency] = useQueryState(
- 'recency',
- queryTypes.integer.withDefault(-1)
- )
// Define transformers for element
function parseElement(query: string) {
@@ -94,9 +93,9 @@ const TeamsRoute: React.FC = (props: Props) => {
// Set the initial parties from props
useEffect(() => {
if (props.teams) {
- setTotalPages(props.teams.total_pages)
- setRecordCount(props.teams.count)
- replaceResults(props.teams.count, props.teams.results)
+ setTotalPages(props.meta.totalPages)
+ setRecordCount(props.meta.count)
+ replaceResults(props.meta.count, props.teams)
}
setCurrentPage(1)
}, [])
@@ -118,24 +117,36 @@ const TeamsRoute: React.FC = (props: Props) => {
const fetchTeams = useCallback(
({ replace }: { replace: boolean }) => {
- const filters = {
+ const filters: {
+ [key: string]: any
+ } = {
+ element: element !== -1 ? element : undefined,
+ raid: raid ? raid.id : undefined,
+ recency: recency !== -1 ? recency : undefined,
+ page: currentPage,
+ }
+
+ Object.keys(filters).forEach(
+ (key) => filters[key] === undefined && delete filters[key]
+ )
+
+ const params = {
params: {
- element: element != -1 ? element : undefined,
- raid: raid ? raid.id : undefined,
- recency: recency != -1 ? recency : undefined,
- page: currentPage,
+ ...filters,
},
}
api.endpoints.parties
- .getAll({ ...filters, ...{ headers: headers } })
+ .getAll(params)
.then((response) => {
- setTotalPages(response.data.total_pages)
- setRecordCount(response.data.count)
+ const results = response.data.results
+ const meta = response.data.meta
- if (replace)
- replaceResults(response.data.count, response.data.results)
- else appendResults(response.data.results)
+ setTotalPages(meta.total_pages)
+ setRecordCount(meta.count)
+
+ if (replace) replaceResults(meta.count, results)
+ else appendResults(results)
})
.catch((error) => handleError(error))
},
@@ -157,12 +168,11 @@ const TeamsRoute: React.FC = (props: Props) => {
// Fetch all raids on mount, then find the raid in the URL if present
useEffect(() => {
api.endpoints.raids.getAll().then((response) => {
- const cleanRaids: Raid[] = response.data.map((r: any) => r.raid)
- setRaids(cleanRaids)
+ setRaids(response.data)
setRaidsLoading(false)
- const raid = cleanRaids.find((r) => r.slug === raidSlug)
+ const raid = response.data.find((r: Raid) => r.slug === raidSlug)
setRaid(raid)
return raid
@@ -193,16 +203,16 @@ const TeamsRoute: React.FC = (props: Props) => {
raidSlug?: string
recency?: number
}) {
- if (element == 0) setElement(0)
- else if (element) setElement(element)
+ if (element == 0) setElement(0, { shallow: true })
+ else if (element) setElement(element, { shallow: true })
if (raids && raidSlug) {
const raid = raids.find((raid) => raid.slug === raidSlug)
setRaid(raid)
- setRaidSlug(raidSlug)
+ setRaidSlug(raidSlug, { shallow: true })
}
- if (recency) setRecency(recency)
+ if (recency) setRecency(recency, { shallow: true })
}
// Methods: Favorites
@@ -212,7 +222,7 @@ const TeamsRoute: React.FC = (props: Props) => {
}
function saveFavorite(teamId: string) {
- api.saveTeam({ id: teamId, params: headers }).then((response) => {
+ api.saveTeam({ id: teamId }).then((response) => {
if (response.status == 201) {
const index = parties.findIndex((p) => p.id === teamId)
const party = parties[index]
@@ -228,7 +238,7 @@ const TeamsRoute: React.FC = (props: Props) => {
}
function unsaveFavorite(teamId: string) {
- api.unsaveTeam({ id: teamId, params: headers }).then((response) => {
+ api.unsaveTeam({ id: teamId }).then((response) => {
if (response.status == 200) {
const index = parties.findIndex((p) => p.id === teamId)
const party = parties[index]
@@ -344,94 +354,43 @@ export const getServerSidePaths = async () => {
// prettier-ignore
export const getServerSideProps = async ({ req, res, locale, query }: { req: NextApiRequest, res: NextApiResponse, locale: string, query: { [index: string]: string } }) => {
- // Cookies
- const cookie = getCookie("account", { req, res })
- const accountData: AccountCookie = cookie
- ? JSON.parse(cookie as string)
- : null
-
- const headers = accountData
- ? { headers: { Authorization: `Bearer ${accountData.token}` } }
- : {}
+ // Set headers for server-side requests
+ setUserToken(req, res)
+ // Fetch and organize raids
let { raids, sortedRaids } = await api.endpoints.raids
- .getAll({ params: headers })
- .then((response) => organizeRaids(response.data.map((r: any) => r.raid)))
-
- // Extract recency filter
- const recencyParam: number = parseInt(query.recency)
-
- // Extract element filter
- const elementParam: string = query.element
- const teamElement: TeamElement | undefined =
- elementParam === "all"
- ? allElement
- : elements.find(
- (element) => element.name.en.toLowerCase() === elementParam
- )
-
- // Extract raid filter
- const raidParam: string = query.raid
- const raid: Raid | undefined = raids.find((r) => r.slug === raidParam)
+ .getAll()
+ .then((response) => organizeRaids(response.data))
// Create filter object
- const filters: {
- raid?: string
- element?: number
- recency?: number
- } = {}
+ const filters: FilterObject = extractFilters(query, raids)
+ const params = {
+ params: { ...filters },
+ }
- if (recencyParam) filters.recency = recencyParam
- if (teamElement && teamElement.id > -1) filters.element = teamElement.id
- if (raid) filters.raid = raid.id
+ // Set up empty variables
+ let teams: Party[] | null = null
+ let meta: PaginationObject = emptyPaginationObject
- // Fetch initial set of parties here
- const response = await api.endpoints.parties.getAll({
- params: {
- ...filters,
- },
- ...headers,
- })
+ // Fetch initial set of parties
+ const response = await api.endpoints.parties.getAll(params)
+
+ // Assign values to pass to props
+ teams = response.data.results
+ meta.count = response.data.meta.count
+ meta.totalPages = response.data.meta.total_pages
+ meta.perPage = response.data.meta.per_page
return {
props: {
- teams: response.data,
+ teams: teams,
+ meta: meta,
raids: raids,
sortedRaids: sortedRaids,
- ...(await serverSideTranslations(locale, ["common"])),
+ ...(await serverSideTranslations(locale, ['common'])),
// Will be passed to the page component as props
},
}
}
-const organizeRaids = (raids: Raid[]) => {
- // Set up empty raid for "All raids"
- const all = {
- id: '0',
- name: {
- en: 'All raids',
- ja: '全て',
- },
- slug: 'all',
- level: 0,
- group: 0,
- element: 0,
- }
-
- const numGroups = Math.max.apply(
- Math,
- raids.map((raid) => raid.group)
- )
- let groupedRaids = []
-
- for (let i = 0; i <= numGroups; i++) {
- groupedRaids[i] = raids.filter((raid) => raid.group == i)
- }
-
- return {
- raids: raids,
- sortedRaids: groupedRaids,
- }
-}
-
export default TeamsRoute
diff --git a/types/User.d.ts b/types/User.d.ts
index 2d344c6c..fdfcedd3 100644
--- a/types/User.d.ts
+++ b/types/User.d.ts
@@ -2,7 +2,7 @@ interface User {
id: string
username: string
granblueId: number
- picture: {
+ avatar: {
picture: string
element: string
}
diff --git a/types/index.d.ts b/types/index.d.ts
index d37ca641..3f8f6723 100644
--- a/types/index.d.ts
+++ b/types/index.d.ts
@@ -7,3 +7,15 @@ export type JobSkillObject = {
2: JobSkill | undefined
3: JobSkill | undefined
}
+
+export type FilterObject = {
+ raid?: string
+ element?: number
+ recency?: number
+}
+
+export type PaginationObject = {
+ count: number
+ totalPages: number
+ perPage: number
+}
diff --git a/utils/api.tsx b/utils/api.tsx
index b8a5987f..5b762cb9 100644
--- a/utils/api.tsx
+++ b/utils/api.tsx
@@ -104,11 +104,16 @@ class Api {
return axios.put(resourceUrl, params)
}
- allSkills(params: {}) {
+ allJobSkills(params?: {}) {
const resourceUrl = `${this.url}/jobs/skills`
return axios.get(resourceUrl, params)
}
+ jobSkillsForJob(jobId: string, params?: {}) {
+ const resourceUrl = `${this.url}/jobs/${jobId}/skills`
+ return axios.get(resourceUrl, params)
+ }
+
savedTeams(params: {}) {
const resourceUrl = `${this.url}/parties/favorites`
return axios.get(resourceUrl, params)
diff --git a/utils/emptyStates.tsx b/utils/emptyStates.tsx
index 973d389e..ae134f44 100644
--- a/utils/emptyStates.tsx
+++ b/utils/emptyStates.tsx
@@ -185,3 +185,9 @@ export const emptyWeaponSeriesState: WeaponSeriesState = {
checked: false,
},
}
+
+export const emptyPaginationObject = {
+ count: 0,
+ totalPages: 0,
+ perPage: 15,
+}
diff --git a/utils/extractFilters.tsx b/utils/extractFilters.tsx
new file mode 100644
index 00000000..efcba098
--- /dev/null
+++ b/utils/extractFilters.tsx
@@ -0,0 +1,26 @@
+import { elements, allElement } from '~utils/Element'
+
+export default (query: { [index: string]: string }, raids: Raid[]) => {
+ // Extract recency filter
+ const recencyParam: number = parseInt(query.recency)
+
+ // Extract element filter
+ const elementParam: string = query.element
+ const teamElement: TeamElement | undefined =
+ elementParam === 'all'
+ ? allElement
+ : elements.find(
+ (element) => element.name.en.toLowerCase() === elementParam
+ )
+
+ // Extract raid filter
+ const raidParam: string = query.raid
+ const raid: Raid | undefined = raids.find((r) => r.slug === raidParam)
+
+ // Return filter object
+ return {
+ recency: recencyParam && recencyParam !== -1 ? recencyParam : undefined,
+ element: teamElement && teamElement.id > -1 ? teamElement.id : undefined,
+ raid: raid ? raid.id : undefined,
+ }
+}
diff --git a/utils/organizeRaids.tsx b/utils/organizeRaids.tsx
new file mode 100644
index 00000000..0bb70430
--- /dev/null
+++ b/utils/organizeRaids.tsx
@@ -0,0 +1,16 @@
+export default (raids: Raid[]) => {
+ const numGroups = Math.max.apply(
+ Math,
+ raids.map((raid) => raid.group)
+ )
+ let groupedRaids = []
+
+ for (let i = 0; i <= numGroups; i++) {
+ groupedRaids[i] = raids.filter((raid) => raid.group == i)
+ }
+
+ return {
+ raids: raids,
+ sortedRaids: groupedRaids,
+ }
+}
diff --git a/utils/setUserToken.tsx b/utils/setUserToken.tsx
new file mode 100644
index 00000000..004a2bc6
--- /dev/null
+++ b/utils/setUserToken.tsx
@@ -0,0 +1,19 @@
+import axios from 'axios'
+import { getCookie } from 'cookies-next'
+import type { NextApiRequest, NextApiResponse } from 'next'
+
+export default (
+ req: NextApiRequest | undefined = undefined,
+ res: NextApiResponse | undefined = undefined
+) => {
+ // Set up cookies
+ const options = req && res ? { req, res } : {}
+ const cookie = getCookie('account', options)
+ if (cookie) {
+ axios.defaults.headers.common['Authorization'] = `Bearer ${
+ JSON.parse(cookie as string).token
+ }`
+ } else {
+ delete axios.defaults.headers.common['Authorization']
+ }
+}