Skip to content

Commit

Permalink
Use searchParams everywhere and use GET endpoints instead of client s…
Browse files Browse the repository at this point in the history
…ide sorting
  • Loading branch information
alianza committed Jun 1, 2024
1 parent 23b3b7f commit bf9cf6f
Show file tree
Hide file tree
Showing 11 changed files with 129 additions and 101 deletions.
35 changes: 27 additions & 8 deletions pages/api/combos/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import dbConnect from '../../../lib/dbConnect';
import Combo from '../../../models/Combo';
import { populateComboName, populateComboTrickName } from '../../../lib/commonUtils';
import { requireAuth } from '../../../lib/serverUtils';
import Grind from '../../../models/Grind';
import Manual from '../../../models/Manual';

export default async function handler(req, res) {
const { method, query } = req;
Expand All @@ -12,18 +14,35 @@ export default async function handler(req, res) {
switch (method) {
case 'GET':
try {
const extraQuery = { ...(query.landedOnly !== undefined && { landed: true }) };
const where = { ...authQuery };

if (query.countOnly !== undefined) {
const count = await Combo.countDocuments({ ...authQuery, ...extraQuery });
if (query.grind === 'true') {
where['trickArray.trickRef'] = Grind.modelName;
}

if (query.manual === 'true') {
where['trickArray.trickRef'] = where['trickArray.trickRef']
? { $all: [where['trickArray.trickRef'], Manual.modelName] }
: Manual.modelName;
}

if (query.landed && query.landed !== 'any') {
where.landed = query.landed === 'true' ? true : { $ne: true }; // If landed is true, set landed to true, otherwise set landed to not true (if landed is false or undefined)
}

if (query.countOnly === 'true') {
const count = await Combo.countDocuments(where);
return res.status(200).json({ success: true, data: count });
}

let combos = await Combo.find({ ...authQuery, ...extraQuery })
.populate('trickArray.trick')
.lean();
combos = combos.map(populateComboTrickName); // Populate every trick name in the combo
combos = combos.map(populateComboName); // Populate every combo name
let combos = await Combo.find(where).populate('trickArray.trick').lean();

if (query.stance && query.stance !== 'all') {
combos = combos.filter(({ trickArray }) => trickArray[0].trick.stance === query.stance); // Filter after populating trickArray.trick to get the populated stance
}

combos = combos.map(populateComboTrickName);
combos = combos.map(populateComboName);
res.status(200).json({ success: true, data: combos });
} catch (error) {
console.error(error);
Expand Down
46 changes: 0 additions & 46 deletions pages/api/combos/search/index.js

This file was deleted.

12 changes: 8 additions & 4 deletions pages/api/flatgroundtricks/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,18 @@ export default async function handler(req, res) {
switch (method) {
case 'GET':
try {
const extraQuery = { ...(query.landedOnly !== undefined && { landed: true }) };
const where = { ...authQuery };

if (query.countOnly !== undefined) {
const count = await FlatgroundTrick.countDocuments({ ...authQuery, ...extraQuery });
if (query.landed && query.landed !== 'any') {
query.landed === 'true' ? (where.landed = true) : (where.landed = { $ne: true }); // If landed is true, set landed to true, otherwise set landed to not true (if landed is false or undefined)
}

if (query.countOnly === 'true') {
const count = await FlatgroundTrick.countDocuments(where);
return res.status(200).json({ success: true, data: count });
}

const flatgroundTricks = await FlatgroundTrick.find({ ...authQuery, ...extraQuery }).lean();
const flatgroundTricks = await FlatgroundTrick.find(where).lean();
const data = flatgroundTricks.map((flatgroundTrick) => ({
...flatgroundTrick,
trick: getFullTrickName(flatgroundTrick),
Expand Down
12 changes: 8 additions & 4 deletions pages/api/grinds/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,18 @@ export default async function handler(req, res) {
switch (method) {
case 'GET':
try {
const extraQuery = { ...(query.landedOnly !== undefined && { landed: true }) };
const where = { ...authQuery };

if (query.countOnly !== undefined) {
const count = await Grind.countDocuments({ ...authQuery, ...extraQuery });
if (query.landed && query.landed !== 'any') {
query.landed === 'true' ? (where.landed = true) : (where.landed = { $ne: true }); // If landed is true, set landed to true, otherwise set landed to not true (if landed is false or undefined)
}

if (query.countOnly === 'true') {
const count = await Grind.countDocuments(where);
return res.status(200).json({ success: true, data: count });
}

const grinds = await Grind.find({ ...authQuery, ...extraQuery }).lean();
const grinds = await Grind.find(where).lean();
const data = grinds.map((grind) => ({ ...grind, trick: getFullGrindName(grind) }));
res.status(200).json({ success: true, data });
} catch (error) {
Expand Down
12 changes: 8 additions & 4 deletions pages/api/manuals/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,18 @@ export default async function handler(req, res) {
switch (method) {
case 'GET':
try {
const extraQuery = { ...(query.landedOnly !== undefined && { landed: true }) };
const where = { ...authQuery };

if (query.countOnly !== undefined) {
const count = await Manual.countDocuments({ ...authQuery, ...extraQuery });
if (query.landed && query.landed !== 'any') {
query.landed === 'true' ? (where.landed = true) : (where.landed = { $ne: true }); // If landed is true, set landed to true, otherwise set landed to not true (if landed is false or undefined)
}

if (query.countOnly === 'true') {
const count = await Manual.countDocuments(where);
return res.status(200).json({ success: true, data: count });
}

const manuals = await Manual.find({ ...authQuery, ...extraQuery }).lean();
const manuals = await Manual.find(where).lean();
const data = manuals.map((manual) => ({ ...manual, trick: getFullManualName(manual) }));
res.status(200).json({ success: true, data });
} catch (error) {
Expand Down
46 changes: 46 additions & 0 deletions pages/api/wishlist/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import dbConnect from '../../../lib/dbConnect';
import FlatgroundTrick from '../../../models/FlatgroundTrick';
import { getFullGrindName, getFullManualName, getFullTrickName } from '../../../lib/commonUtils';
import { requireAuth } from '../../../lib/serverUtils';
import Grind from '../../../models/Grind';
import Manual from '../../../models/Manual';

export default async function handler(req, res) {
const { method, query } = req;

await dbConnect();
const { authQuery } = await requireAuth(req, res);

switch (method) {
case 'GET':
try {
const where = { ...authQuery };

if (query.countOnly === 'true') {
const count = await FlatgroundTrick.countDocuments({ ...authQuery, ...extraQuery });
return res.status(200).json({ success: true, data: count });
}

const flatgroundTricks = await FlatgroundTrick.find({ ...authQuery, ...extraQuery }).lean();
const flatgroundTricksData = flatgroundTricks.map((flatgroundTrick) => ({
...flatgroundTrick,
trick: getFullTrickName(flatgroundTrick),
}));

const grinds = await Grind.find({ ...authQuery, ...extraQuery }).lean();
const grindsData = grinds.map((grind) => ({ ...grind, trick: getFullGrindName(grind) }));

const manuals = await Manual.find({ ...authQuery, ...extraQuery }).lean();
const manualsData = manuals.map((manual) => ({ ...manual, trick: getFullManualName(manual) }));

res.status(200).json({ success: true, data });
} catch (error) {
console.error(error);
res.status(400).json({ success: false, error: error.message });
}
break;
default:
res.status(400).json({ success: false, error: `Unhandled request method: ${method}` });
break;
}
}
12 changes: 5 additions & 7 deletions pages/combos/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ export default function CombosPage() {

useAsyncEffect(async () => {
try {
const { data } = await apiCall('combos/search', { method: 'POST', body: JSON.stringify(filters) });
const params = new URLSearchParams(stringifyValues(filters));
const { data } = await apiCall(`combos?${params}`, { method: 'GET' });
setCombos(data);
} catch (error) {
setCombos([]);
Expand All @@ -46,9 +47,6 @@ export default function CombosPage() {
}
};

const filteredCombos =
filters.landed === 'any' ? combos : combos?.filter((combo) => filters.landed === (combo.landed ? 'yes' : 'no'));

return (
<div className="flex flex-col gap-12">
<div>
Expand Down Expand Up @@ -103,15 +101,15 @@ export default function CombosPage() {
Any
</option>
<hr />
<option value="yes">Yes</option>
<option value="no">No</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
</label>
</Filters>

<TransitionScroll hiddenStyle={hiddenStyle} baseStyle={baseStyle} className="flex flex-col">
<GenericTable
objArray={filteredCombos}
objArray={combos}
columns={[{ trick: { className: 'text-sm font-bold', alias: 'Combo name' } }, landedAtCol]}
actions={getCommonActions('combos')}
onAction={handleAction}
Expand Down
9 changes: 6 additions & 3 deletions pages/dashboard.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ export default function Index() {
useAsyncEffect(async () => {
const fetchAndSetData = async (endpoint, setData) => {
try {
const { data } = await apiCall(`${endpoint}?landedOnly=true`, { method: 'GET' });
const params = new URLSearchParams({ landed: 'true' });
const { data } = await apiCall(`${endpoint}?${params}`, { method: 'GET' });
setData((prevData) => ({ ...prevData, data }));
} catch (error) {
toast.error(`Failed to fetch ${endpoint}: ${error.message}`);
Expand All @@ -52,7 +53,8 @@ export default function Index() {

const fetchAndSetCount = async (endpoint, setData) => {
try {
const { data } = await apiCall(`${endpoint}?countOnly=true`, { method: 'GET' });
const params = new URLSearchParams({ countOnly: 'true' });
const { data } = await apiCall(`${endpoint}?${params}`, { method: 'GET' });
setData((prevData) => ({ ...prevData, count: data }));
} catch (error) {
toast.error(`Failed to fetch total ${endpoint} count: ${error.message}`);
Expand Down Expand Up @@ -87,8 +89,9 @@ export default function Index() {
if (!confirm(`Are you sure you want to delete "${obj.trick}"?`)) return;
const [endpoint, setData] = endpointSetterMap[entityType];
if (!endpoint) return toast.error(`Failed to delete ${obj.trick}: Invalid entity type: ${entityType}`);
const params = new URLSearchParams({ landed: 'true' });
await apiCall(endpoint, { method: 'DELETE', id: obj._id });
const { data } = await apiCall(`${endpoint}?landedOnly=true`, { method: 'GET' });
const { data } = await apiCall(`${endpoint}?${params}`, { method: 'GET' });
setData((prevData) => ({ ...prevData, data }));
toast.success(`Successfully deleted ${obj.trick}`);
} catch (error) {
Expand Down
17 changes: 7 additions & 10 deletions pages/flatgroundtricks/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { apiCall, baseStyle, getCommonActions, hiddenStyle, landedAtCol, trickCo
import GenericTable from '../../components/common/genericTable/GenericTable';
import TransitionScroll from 'react-transition-scroll';
import Filters from '../../components/common/Filters';
import { stringifyValues } from '../../lib/commonUtils';

const defaultFilters = { landed: 'any' };

Expand All @@ -14,13 +15,14 @@ export default function FlatgroundTricksPage() {

useAsyncEffect(async () => {
try {
const { data } = await apiCall('flatgroundtricks', { method: 'GET' });
const searchParams = new URLSearchParams(stringifyValues(filters));
const { data } = await apiCall(`flatgroundtricks`, { method: 'GET', searchParams });
setFlatgroundTricks(data);
} catch (error) {
setFlatgroundTricks([]);
toast.error(`Failed to load Flatground Tricks: ${error.message}`);
}
}, []);
}, [filters]);

const handleAction = async (action, obj) => {
switch (action) {
Expand All @@ -38,11 +40,6 @@ export default function FlatgroundTricksPage() {
}
};

const filteredFlatgroundTricks =
filters.landed === 'any'
? flatgroundTricks
: flatgroundTricks?.filter((trick) => filters.landed === (trick.landed ? 'yes' : 'no'));

return (
<div className="flex flex-col gap-12">
<div>
Expand All @@ -66,15 +63,15 @@ export default function FlatgroundTricksPage() {
Any
</option>
<hr />
<option value="yes">Yes</option>
<option value="no">No</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
</label>
</Filters>

<TransitionScroll hiddenStyle={hiddenStyle} baseStyle={baseStyle} className="flex flex-col">
<GenericTable
objArray={filteredFlatgroundTricks}
objArray={flatgroundTricks}
columns={['stance', 'direction', 'rotation', 'name', trickCol, landedAtCol]}
actions={getCommonActions('flatgroundtricks')}
onAction={handleAction}
Expand Down
14 changes: 7 additions & 7 deletions pages/grinds/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { apiCall, baseStyle, getCommonActions, hiddenStyle, landedAtCol, trickCo
import GenericTable from '../../components/common/genericTable/GenericTable';
import TransitionScroll from 'react-transition-scroll';
import Filters from '../../components/common/Filters';
import { stringifyValues } from '../../lib/commonUtils';

const defaultFilters = { landed: 'any' };

Expand All @@ -14,13 +15,14 @@ export default function GrindsPage() {

useAsyncEffect(async () => {
try {
const { data } = await apiCall('grinds', { method: 'GET' });
const searchParams = new URLSearchParams(stringifyValues(filters));
const { data } = await apiCall('grinds', { method: 'GET', searchParams });
setGrinds(data);
} catch (error) {
setGrinds([]);
toast.error(`Failed to load grinds: ${error.message}`);
}
}, []);
}, [filters]);

const handleAction = async (action, obj) => {
switch (action) {
Expand All @@ -37,8 +39,6 @@ export default function GrindsPage() {
break;
}
};
const filteredGrinds =
filters.landed === 'any' ? grinds : grinds.filter((grind) => filters.landed === (grind.landed ? 'yes' : 'no'));

return (
<div className="flex flex-col gap-12">
Expand All @@ -60,15 +60,15 @@ export default function GrindsPage() {
Any
</option>
<hr />
<option value="yes">Yes</option>
<option value="no">No</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
</label>
</Filters>

<TransitionScroll hiddenStyle={hiddenStyle} baseStyle={baseStyle} className="flex flex-col">
<GenericTable
objArray={filteredGrinds}
objArray={grinds}
columns={['stance', 'direction', 'name', trickCol, landedAtCol]}
actions={getCommonActions('grinds')}
entityName="grind"
Expand Down
Loading

0 comments on commit bf9cf6f

Please sign in to comment.