diff --git a/pages/[username].tsx b/pages/[username].tsx index 3e64897c..52c4d7e7 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,6 +9,7 @@ import InfiniteScroll from 'react-infinite-scroll-component' import { serverSideTranslations } from 'next-i18next/serverSideTranslations' import api from '~utils/api' +import setUserToken from '~utils/setUserToken' import useDidMountEffect from '~utils/useDidMountEffect' import { elements, allElement } from '~utils/Element' @@ -19,6 +19,7 @@ import FilterBar from '~components/FilterBar' import type { NextApiRequest, NextApiResponse } from 'next' import type { PaginationObject } from '~types' +import type { FilterObject, PaginationObject } from '~types' interface Props { user?: User @@ -29,15 +30,6 @@ interface Props { } 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 @@ -139,7 +131,7 @@ const ProfileRoute: React.FC = (props: Props) => { api.endpoints.users .getOne({ id: username, - params: { ...filters, ...{ headers: headers } }, + params: { ...filters }, }) .then((response) => { const results = response.data.profile.parties @@ -336,18 +328,12 @@ 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 }) + .getAll() .then((response) => organizeRaids(response.data)) // Extract recency filter @@ -376,8 +362,11 @@ export const getServerSideProps = async ({ req, res, locale, query }: { req: Nex if (recencyParam) filters.recency = recencyParam if (teamElement && teamElement.id > -1) filters.element = teamElement.id if (raid) filters.raid = raid.id + const params = { + params: { ...filters }, + } - // Fetch initial set of parties here + // Set up empty variables let user: User | null = null let teams: Party[] | null = null let meta: PaginationObject = { @@ -389,10 +378,7 @@ export const getServerSideProps = async ({ req, res, locale, query }: { req: Nex if (query.username) { const response = await api.endpoints.users.getOne({ id: query.username, - params: { - ...filters, - }, - ...headers, + params, }) user = response.data.profile 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 a516bc5b..3fe1eb74 100644 --- a/pages/new/index.tsx +++ b/pages/new/index.tsx @@ -1,10 +1,10 @@ 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 setUserToken from '~utils/setUserToken' import api from '~utils/api' import type { NextApiRequest, NextApiResponse } from 'next' @@ -47,27 +47,23 @@ 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 }) + .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.allSkills().then((response) => { + return response.data + }) + return { props: { jobs: jobs, diff --git a/pages/saved.tsx b/pages/saved.tsx index 66072d21..7fa2880b 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,6 +10,7 @@ import { serverSideTranslations } from 'next-i18next/serverSideTranslations' import clonedeep from 'lodash.clonedeep' import api from '~utils/api' +import setUserToken from '~utils/setUserToken' import useDidMountEffect from '~utils/useDidMountEffect' import { elements, allElement } from '~utils/Element' @@ -29,15 +29,6 @@ interface Props { } 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() @@ -219,7 +210,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] @@ -235,7 +226,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] @@ -343,18 +334,12 @@ 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 }) + .getAll() .then((response) => organizeRaids(response.data)) // Extract recency filter @@ -383,6 +368,9 @@ export const getServerSideProps = async ({ req, res, locale, query }: { req: Nex if (recencyParam) filters.recency = recencyParam if (teamElement && teamElement.id > -1) filters.element = teamElement.id if (raid) filters.raid = raid.id + const params = { + params: { ...filters }, + } let teams: Party[] | null = null let meta: PaginationObject = { @@ -391,14 +379,8 @@ export const getServerSideProps = async ({ req, res, locale, query }: { req: Nex perPage: 15, } - // 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) teams = response.data.results meta.count = response.data.meta.count meta.totalPages = response.data.meta.total_pages diff --git a/pages/teams.tsx b/pages/teams.tsx index 8c47365c..7cb40316 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,6 +10,7 @@ import { serverSideTranslations } from 'next-i18next/serverSideTranslations' import clonedeep from 'lodash.clonedeep' import api from '~utils/api' +import setUserToken from '~utils/setUserToken' import useDidMountEffect from '~utils/useDidMountEffect' import { elements, allElement } from '~utils/Element' @@ -28,15 +28,6 @@ interface Props { } 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() @@ -133,7 +124,7 @@ const TeamsRoute: React.FC = (props: Props) => { } api.endpoints.parties - .getAll({ ...filters, ...{ headers: headers } }) + .getAll(params) .then((response) => { const results = response.data.results const meta = response.data.meta @@ -218,7 +209,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] @@ -234,7 +225,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] @@ -350,18 +341,12 @@ 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 }) + .getAll() .then((response) => organizeRaids(response.data)) // Extract recency filter @@ -390,6 +375,9 @@ export const getServerSideProps = async ({ req, res, locale, query }: { req: Nex if (recencyParam) filters.recency = recencyParam if (teamElement && teamElement.id > -1) filters.element = teamElement.id if (raid) filters.raid = raid.id + const params = { + params: { ...filters }, + } let teams: Party[] | null = null let meta: PaginationObject = { @@ -398,13 +386,8 @@ export const getServerSideProps = async ({ req, res, locale, query }: { req: Nex perPage: 15, } - // 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) teams = response.data.results meta.count = response.data.meta.count diff --git a/utils/api.tsx b/utils/api.tsx index b8a5987f..5ca27d92 100644 --- a/utils/api.tsx +++ b/utils/api.tsx @@ -104,7 +104,7 @@ class Api { return axios.put(resourceUrl, params) } - allSkills(params: {}) { + allSkills(params?: {}) { const resourceUrl = `${this.url}/jobs/skills` return axios.get(resourceUrl, params) } 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'] + } +}