Skip to content

Commit

Permalink
Ensure errors are returned as response
Browse files Browse the repository at this point in the history
  • Loading branch information
nathsimpson committed Oct 4, 2023
1 parent baebea0 commit 2f760fe
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 31 deletions.
2 changes: 0 additions & 2 deletions components/Home/Dribbble/Dribbble.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import React from 'react';

import { Stack } from '../../ui/box';
import { Heading, Text } from '../../ui/typography';
import { TextLink } from '../../TextLink';
Expand Down
59 changes: 30 additions & 29 deletions pages/api/get-dribbble-shots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@ type DribbbleShot = {
link: string;
};

type Data = {
type ResponseData = {
shots: DribbbleShot[];
};

type ResponseError = {
error: string;
};

// Return type from Dribbble API
type DribbbleApiShot = {
description: string;
Expand All @@ -25,38 +29,35 @@ type DribbbleApiShot = {
const ACCESS_TOKEN = process.env.DRIBBBLE_ACCESS_TOKEN;
const API_ENDPOINT = `https://api.dribbble.com/v2/user/shots?access_token=${ACCESS_TOKEN}`;

const getDribbbleShots = async (): Promise<DribbbleShot[]> => {
const dribbbleShots = fetch(API_ENDPOINT, {
headers: { Accept: 'application/json' }
})
.then((response) => response.json())

.then((data) => {
return (data as DribbbleApiShot[])
.map((shot) => ({
description: shot.description.replace(/(<([^>]+)>)/gi, ''),
imageUrl: shot.images.normal,
link:
shot.images && (shot.images.hidpi || shot.images.normal)
? shot.images.hidpi || shot.images.normal
: shot.html_url
}))
.filter((shot) => !shot.imageUrl.includes('.gif'));
});

return dribbbleShots;
const formatShots = (shots: DribbbleApiShot[]): DribbbleShot[] => {
return shots
.map((shot) => ({
description: shot.description.replace(/(<([^>]+)>)/gi, ''),
imageUrl: shot.images.normal,
link:
shot.images && (shot.images.hidpi || shot.images.normal)
? shot.images.hidpi || shot.images.normal
: shot.html_url
}))
.filter((shot) => !shot.imageUrl.includes('.gif'));
};

export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
res: NextApiResponse<ResponseData | ResponseError>
) {
return getDribbbleShots()
.then((shots) => {
res.status(200).json({ shots });
await fetch(API_ENDPOINT, {
headers: { Accept: 'application/json' }
})
.then((response) => {
if (!response.ok) {
throw new Error("Unsuccessful response from Dribbble's API");
}

return response.json().then((data) => {
const formatted = formatShots(data as DribbbleApiShot[]);
return res.status(200).json({ shots: formatted });
});
})
.catch((error) => ({
statusCode: 422,
body: JSON.stringify(error)
}));
.catch((error) => res.status(422).json({ error }));
}

0 comments on commit 2f760fe

Please sign in to comment.