refactor(frontend): some degree of api wrapping

This commit is contained in:
hanabi 2022-11-24 14:44:47 -05:00
parent f4a63fc95e
commit ba24815320
11 changed files with 365 additions and 222 deletions

View file

@ -6,8 +6,7 @@ import NavItem from "./NavItem";
import Logo from "./logo"; import Logo from "./logo";
import { useRecoilState } from "recoil"; import { useRecoilState } from "recoil";
import { userState } from "../lib/state"; import { userState } from "../lib/state";
import fetchAPI from "../lib/fetch"; import { fetchAPI, APIError, ErrorCode, MeUser } from "../lib/api-fetch";
import { APIError, ErrorCode, MeUser } from "../lib/types";
export default function Navigation() { export default function Navigation() {
const [user, setUser] = useRecoilState(userState); const [user, setUser] = useRecoilState(userState);

View file

@ -1,14 +1,4 @@
import Head from "next/head"; import Head from "next/head";
import {
Field,
Member,
Name,
PartialPerson,
Person,
Pronoun,
User,
WordStatus,
} from "../lib/types";
import ReactMarkdown from "react-markdown"; import ReactMarkdown from "react-markdown";
import { userState } from "../lib/state"; import { userState } from "../lib/state";
import { useRecoilValue } from "recoil"; import { useRecoilValue } from "recoil";
@ -23,12 +13,13 @@ import {
import BlueLink from "./BlueLink"; import BlueLink from "./BlueLink";
import React from "react"; import React from "react";
import Card from "./Card"; import Card from "./Card";
import { Field, Label, LabelStatus, Person, User } from "../lib/api";
export default function PersonPage({ person }: { person: Person }) { export default function PersonPage({ person }: { person: Person }) {
return ( return (
<> <>
<Head> <Head>
<title key="title">{`${personFullHandle(person)} - pronouns.cc`}</title> <title key="title">{`${person.fullHandle()} - pronouns.cc`}</title>
</Head> </Head>
<PersonHead person={person} /> <PersonHead person={person} />
<IsOwnUserPageNotice person={person} /> <IsOwnUserPageNotice person={person} />
@ -47,97 +38,42 @@ export default function PersonPage({ person }: { person: Person }) {
<PersonAvatar person={person} /> <PersonAvatar person={person} />
<PersonInfo person={person} /> <PersonInfo person={person} />
</div> </div>
<LabelList content={person.names ?? []} /> <LabelList content={person.names} />
<LabelList content={person.pronouns ?? []} /> <LabelList content={person.pronouns} />
<FieldCardGrid fields={person.fields ?? []} /> <FieldCardGrid fields={person.fields} />
{"user" in person ? ( {person instanceof User ? (
<BlueLink to={personURL(person.user)}>{`< ${ <MemberList user={person} />
person.user.display_name ?? person.user.name
}`}</BlueLink>
) : ( ) : (
<MemberList user={person as any as User} /> <BlueLink
to={person.relativeURL()}
>{`< ${person.display()}`}</BlueLink>
)} )}
</div> </div>
</> </>
); );
} }
/** Full handle of a person. */
function personFullHandle(person: Person) {
return "user" in person
? `&${person.name}@${person.user.name}`
: `@${person.name}`;
}
/** Short handle of a person. */
function personShortHandle(person: Person) {
return ("user" in person ? "&" : "@") + person.name;
}
/** The user (account) associated with a person. */
function personUser(person: Person) {
return "user" in person ? person.user : person;
}
/** The (relative) URL pointing to a person. */
function personURL(person: PartialPerson | Member) {
const domain =
typeof window !== "undefined" ? window.location.origin : process.env.DOMAIN;
return `${domain}/u/${"user" in person ? `${person.user.name}/` : ""}${
person.name
}`;
}
function PersonHead({ person }: { person: Person }) { function PersonHead({ person }: { person: Person }) {
const { const { displayName, avatarUrls, bio, names, pronouns } = person;
id,
name,
display_name,
avatar_urls,
bio,
links,
names,
pronouns,
fields,
} = person;
let description = ""; let description = "";
if ( const favNames = names.filter((x) => x.status === LabelStatus.Favourite);
names?.filter((name) => name.status === WordStatus.Favourite)?.length && const favPronouns = pronouns.filter(
pronouns?.filter((pronoun) => pronoun.status === WordStatus.Favourite) (x) => x.status === LabelStatus.Favourite
?.length );
) { if (favNames.length || favPronouns.length) {
description = `${personShortHandle(person)} goes by ${names description = `${person.shortHandle()}${
.filter((name) => name.status === WordStatus.Favourite) favNames.length
.map((name) => name.name) ? ` goes by ${favNames.map((x) => x.display()).join(", ")}`
.join(", ")} and uses ${pronouns : ""
.filter((pronoun) => pronoun.status === WordStatus.Favourite) }${favNames.length && favPronouns.length ? " and" : ""}${
.map( favPronouns.length
(pronoun) => ? `uses ${favPronouns
pronoun.display_text ?? .map((x) => x.shortDisplay())
pronoun.pronouns.split("/").slice(0, 2).join("/") .join(", ")} pronouns.`
) : ""
.join(", ")} pronouns.`; }`;
} else if (
names?.filter((name) => name.status === WordStatus.Favourite)?.length
) {
description = `${personShortHandle(person)} goes by ${names
.filter((name) => name.status === WordStatus.Favourite)
.map((name) => name.name)
.join(", ")}.`;
} else if (
pronouns?.filter((pronoun) => pronoun.status === WordStatus.Favourite)
?.length
) {
description = `${personShortHandle(person)} uses ${pronouns
.filter((pronoun) => pronoun.status === WordStatus.Favourite)
.map(
(pronoun) =>
pronoun.display_text ??
pronoun.pronouns.split("/").slice(0, 2).join("/")
)
.join(", ")} pronouns.`;
} else if (bio && bio !== "") { } else if (bio && bio !== "") {
description = bio.slice(0, 500); description = `${bio.slice(0, 500)}${bio.length > 500 ? "…" : ""}`;
} }
return ( return (
@ -147,22 +83,20 @@ function PersonHead({ person }: { person: Person }) {
key="og:title" key="og:title"
property="og:title" property="og:title"
content={ content={
display_name displayName
? `${display_name} (${personFullHandle(person)})` ? `${displayName} (${person.fullHandle()})`
: personFullHandle(person) : person.fullHandle()
} }
/> />
{avatar_urls && avatar_urls.length > 0 ? ( {avatarUrls && avatarUrls.length > 0 && (
<meta key="og:image" property="og:image" content={avatar_urls[0]} /> <meta key="og:image" property="og:image" content={avatarUrls[0]} />
) : (
<></>
)} )}
<meta <meta
key="og:description" key="og:description"
property="og:description" property="og:description"
content={description} content={description}
/> />
<meta key="og:url" property="og:url" content={personURL(person)} /> <meta key="og:url" property="og:url" content={person.absoluteURL()} />
</Head> </Head>
); );
} }
@ -180,15 +114,15 @@ function IsOwnUserPageNotice({ person }: { person: Person }) {
} }
function MemberList({ user, className }: { user: User; className?: string }) { function MemberList({ user, className }: { user: User; className?: string }) {
const partialMembers = user.members; const partialMembers = user.partialMembers;
return ( return (
<div className={`mx-auto flex-col items-center ${className || ""}`}> <div className={`mx-auto flex-col items-center ${className || ""}`}>
<h1 className="text-2xl">Members</h1> <h1 className="text-2xl">Members</h1>
<ul> <ul>
{partialMembers?.map((partialMember) => ( {partialMembers.map((partialMember) => (
<li className='before:[content:"-_"]' key={partialMember.id}> <li className='before:[content:"-_"]' key={partialMember.id}>
<BlueLink to={`/u/${user.name}/${partialMember.name}`}> <BlueLink to={`/u/${user.name}/${partialMember.name}`}>
<span>{partialMember.display_name ?? partialMember.name}</span> <span>{partialMember.displayName ?? partialMember.name}</span>
</BlueLink> </BlueLink>
</li> </li>
))} ))}
@ -198,12 +132,12 @@ function MemberList({ user, className }: { user: User; className?: string }) {
} }
function PersonAvatar({ person }: { person: Person }) { function PersonAvatar({ person }: { person: Person }) {
const { display_name, name, avatar_urls } = person; const { displayName, name, avatarUrls } = person;
return avatar_urls && avatar_urls.length !== 0 ? ( return avatarUrls && avatarUrls.length !== 0 ? (
<FallbackImage <FallbackImage
className="max-w-xs rounded-full" className="max-w-xs rounded-full"
urls={avatar_urls} urls={avatarUrls}
alt={`${display_name || name}'s avatar`} alt={`${displayName || name}'s avatar`}
/> />
) : ( ) : (
<></> <></>
@ -211,16 +145,16 @@ function PersonAvatar({ person }: { person: Person }) {
} }
function PersonInfo({ person }: { person: Person }) { function PersonInfo({ person }: { person: Person }) {
const { display_name, name, bio, links } = person; const { displayName, name, bio, links } = person;
return ( return (
<div className="flex flex-col"> <div className="flex flex-col">
{/* name */} {/* name */}
<h1 className="text-2xl font-bold"> <h1 className="text-2xl font-bold">
{display_name === null ? name : display_name} {displayName === null ? name : displayName}
</h1> </h1>
{/* handle */} {/* handle */}
<h3 className="text-xl font-light text-slate-600 dark:text-slate-400"> <h3 className="text-xl font-light text-slate-600 dark:text-slate-400">
{personFullHandle(person)} {person.fullHandle()}
</h3> </h3>
{/* bio */} {/* bio */}
{bio && ( {bio && (
@ -229,7 +163,7 @@ function PersonInfo({ person }: { person: Person }) {
</ReactMarkdown> </ReactMarkdown>
)} )}
{/* links */} {/* links */}
{links?.length && ( {links.length > 0 && (
<div className="flex flex-col mx-auto lg:ml-auto"> <div className="flex flex-col mx-auto lg:ml-auto">
{links.map((link, index) => ( {links.map((link, index) => (
<a <a
@ -247,8 +181,8 @@ function PersonInfo({ person }: { person: Person }) {
); );
} }
function LabelList({ content }: { content: Name[] | Pronoun[] }) { function LabelList({ content }: { content: Label[] }) {
return content?.length > 0 ? ( return content.length > 0 ? (
<div className="border-b border-slate-200 dark:border-slate-700"> <div className="border-b border-slate-200 dark:border-slate-700">
{content.map((label, index) => ( {content.map((label, index) => (
<LabelLine key={index} label={label} /> <LabelLine key={index} label={label} />
@ -259,63 +193,62 @@ function LabelList({ content }: { content: Name[] | Pronoun[] }) {
); );
} }
function LabelStatusIcon({ status }: { status: WordStatus }) { function LabelStatusIcon({ status }: { status: LabelStatus }) {
return React.createElement( return React.createElement(
{ {
[WordStatus.Favourite]: HeartFill, [LabelStatus.Favourite]: HeartFill,
[WordStatus.Okay]: HandThumbsUp, [LabelStatus.Okay]: HandThumbsUp,
[WordStatus.Jokingly]: EmojiLaughing, [LabelStatus.Jokingly]: EmojiLaughing,
[WordStatus.FriendsOnly]: People, [LabelStatus.FriendsOnly]: People,
[WordStatus.Avoid]: HandThumbsDown, [LabelStatus.Avoid]: HandThumbsDown,
}[status], }[status],
{ className: "inline" } { className: "inline" }
); );
} }
function LabelsLine({ labels }: { labels: Name[] | Pronoun[] }) { function LabelsLine({
if (!labels?.length) return <></>; status,
const status = labels[0].status; texts,
const text = labels }: {
.map((label) => status: LabelStatus;
"name" in label texts: string[];
? label.name }) {
: label.display_text ?? label.pronouns.split("/").slice(0, 2).join("/") return !texts.length ? (
) <></>
.join(", "); ) : (
return (
<p <p
className={` className={`
${status === WordStatus.Favourite ? "text-lg font-bold" : ""} ${status === LabelStatus.Favourite ? "text-lg font-bold" : ""}
${ ${
status === WordStatus.Avoid ? "text-slate-600 dark:text-slate-400" : "" status === LabelStatus.Avoid ? "text-slate-600 dark:text-slate-400" : ""
}`} }`}
> >
<LabelStatusIcon status={status} /> {text} <LabelStatusIcon status={status} /> {texts.join(", ")}
</p> </p>
); );
} }
function LabelLine({ label }: { label: Name | Pronoun }) { function LabelLine({ label }: { label: Label }) {
return <LabelsLine labels={[label] as Name[] | Pronoun[]} />; return <LabelsLine status={label.status} texts={[label.display()]} />;
} }
function FieldCardGrid({ fields }: { fields: Field[] }) { function FieldCardGrid({ fields }: { fields: Field[] }) {
return ( return (
<div className="flex flex-col md:flex-row gap-4 py-2 [&>*]:flex-1"> <div className="flex flex-col md:flex-row gap-4 py-2 [&>*]:flex-1">
{fields?.map((field, index) => ( {fields.map((field, index) => (
<FieldCard field={field} key={index} /> <FieldCard field={field} key={index} />
))} ))}
</div> </div>
); );
} }
const fieldEntryStatus: { [key in string]: WordStatus } = { const labelStatusOrder: LabelStatus[] = [
favourite: WordStatus.Favourite, LabelStatus.Favourite,
okay: WordStatus.Okay, LabelStatus.Okay,
jokingly: WordStatus.Jokingly, LabelStatus.Jokingly,
friends_only: WordStatus.FriendsOnly, LabelStatus.FriendsOnly,
avoid: WordStatus.Avoid, LabelStatus.Avoid,
}; ];
function FieldCard({ function FieldCard({
field, field,
@ -326,13 +259,13 @@ function FieldCard({
}) { }) {
return ( return (
<Card title={field.name} draggable={draggable}> <Card title={field.name} draggable={draggable}>
{Object.entries(fieldEntryStatus).map(([statusName, status], i) => ( {labelStatusOrder.map((status, i) => (
<LabelsLine <LabelsLine
key={i} key={i}
labels={(field as any)[statusName]?.map((name: string) => ({ status={status}
name, texts={field.labels
status, .filter((x) => x.status === status)
}))} .map((x) => x.display())}
/> />
))} ))}
</Card> </Card>

View file

@ -1,28 +1,36 @@
/** An array returned by the API. (Can be `null` due to a quirk in Go.) */
export type Arr<T> = T[] | null;
export interface PartialPerson { export interface PartialPerson {
id: string; id: string;
name: string; name: string;
display_name: string | null; display_name: string | null;
avatar_urls: string[] | null; avatar_urls: Arr<string>;
} }
export type PartialUser = PartialPerson; export type PartialUser = PartialPerson;
export type PartialMember = PartialPerson; export type PartialMember = PartialPerson;
interface _Person extends PartialPerson { /** The shared interface of `Member` and `User`.
* A typical `_Person` is only one of those two, so consider using `Person` instead.
*/
export interface _Person extends PartialPerson {
bio: string | null; bio: string | null;
links: string[] | null; links: Arr<string>;
names: Name[] | null; names: Arr<Name>;
pronouns: Pronoun[] | null; pronouns: Arr<Pronoun>;
fields: Field[] | null; fields: Arr<Field>;
}
export interface User extends _Person {
members: Arr<PartialMember>;
} }
export interface Member extends _Person { export interface Member extends _Person {
user: PartialUser; user: PartialUser;
} }
export interface User extends _Person {
members: PartialMember[] | null;
}
export type Person = Member | User; export type Person = Member | User;
export interface MeUser extends User { export interface MeUser extends User {
@ -43,11 +51,11 @@ export interface Pronoun {
export interface Field { export interface Field {
name: string; name: string;
favourite: string[] | null; favourite: Arr<string>;
okay: string[] | null; okay: Arr<string>;
jokingly: string[] | null; jokingly: Arr<string>;
friends_only: string[] | null; friends_only: Arr<string>;
avoid: string[] | null; avoid: Arr<string>;
} }
export interface APIError { export interface APIError {
@ -101,3 +109,28 @@ export interface SignupResponse {
user: MeUser; user: MeUser;
token: string; token: string;
} }
const apiBase = process.env.API_BASE ?? "/api";
export async function fetchAPI<T>(
path: string,
method = "GET",
body: any = null
) {
const token =
typeof localStorage !== "undefined" &&
localStorage.getItem("pronouns-token");
const resp = await fetch(`${apiBase}/v1${path}`, {
method,
headers: {
...token ? { Authorization: token } : {},
"Content-Type": "application/json",
},
body: body ? JSON.stringify(body) : null,
});
const data = await resp.json();
if (resp.status < 200 || resp.status >= 300) throw data as APIError;
return data as T;
}

209
frontend/lib/api.ts Normal file
View file

@ -0,0 +1,209 @@
import * as API from "./api-fetch";
import { fetchAPI } from './api-fetch';
function getDomain(): string {
const domain = typeof window !== "undefined" ? window.location.origin : process.env.DOMAIN;
if (!domain) throw new Error('process.env.DOMAIN not set');
return domain;
}
export class PartialPerson {
id: string;
name: string;
displayName: string | null;
avatarUrls: string[];
constructor({ id, name, display_name, avatar_urls }: API.PartialPerson) {
this.id = id;
this.name = name;
this.displayName = display_name;
this.avatarUrls = avatar_urls ?? [];
}
display(): string {
return this.displayName ?? this.name;
}
}
export class PartialUser extends PartialPerson {}
export class PartialMember extends PartialPerson {}
abstract class _Person extends PartialPerson {
bio: string | null;
links: string[];
names: Name[];
pronouns: Pronouns[];
fields: Field[];
constructor(apiData: API._Person) {
super(apiData);
const { bio, links, names, pronouns, fields } = apiData;
this.bio = bio;
this.links = links ?? [];
this.names = (names ?? []).map(x => new Name(x));
this.pronouns = (pronouns ?? []).map(x => new Pronouns(x));
this.fields = (fields ?? []).map(x => new Field(x));
}
abstract fullHandle(): string
shortHandle(): string {
return this.fullHandle();
}
abstract relativeURL(): string
absoluteURL(): string {
return `${getDomain()}${this.relativeURL()}`;
}
}
export class User extends _Person {
partialMembers: PartialMember[];
constructor(apiData: API.User) {
super(apiData);
const { members } = apiData;
this.partialMembers = (members ?? []).map(x => new PartialMember(x));
}
static async fetchFromName(name: string): Promise<User> {
return new User(await fetchAPI<API.User>(`/users/${name}`));
}
fullHandle(): string {
return `@${this.name}`;
}
shortHandle(): string {
return this.fullHandle();
}
relativeURL(): string {
return `/u/${this.name}`;
}
}
export class Member extends _Person {
partialUser: PartialUser;
constructor(apiData: API.Member) {
super(apiData);
const { user } = apiData;
this.partialUser = new PartialUser(user);
}
static async fetchFromUserAndMemberName(userName: string, memberName: string): Promise<Member> {
return new Member(await fetchAPI<API.Member>(`/users/${userName}/members/${memberName}`));
}
fullHandle(): string {
return `${this.name}@${this.partialUser.name}`;
}
relativeURL(): string {
return `/u/${this.partialUser.name}/${this.name}`;
}
}
export type Person = Member | User;
export class MeUser extends User {
discord: string | null;
discordUsername: string | null;
constructor(apiData: API.MeUser) {
super(apiData);
const { discord, discord_username } = apiData;
this.discord = discord;
this.discordUsername = discord_username;
}
static async fetchMe(): Promise<MeUser> {
return new MeUser(await fetchAPI<API.MeUser>("/users/@me"));
}
}
export enum LabelType {
Name = 1,
Pronouns = 2,
Unspecified = 3,
}
export const LabelStatus = API.WordStatus;
export type LabelStatus = API.WordStatus;
export interface LabelData {
type?: LabelType
displayText: string | null
text: string
status: LabelStatus
}
export class Label {
type: LabelType;
displayText: string | null;
text: string;
status: LabelStatus;
constructor({ type, displayText, text, status }: LabelData) {
this.type = type ?? LabelType.Unspecified;
this.displayText = displayText;
this.text = text;
this.status = status;
}
display(): string {
return this.displayText ?? this.text;
}
shortDisplay(): string {
return this.display();
}
}
export class Name extends Label {
constructor({ name, status }: API.Name) {
super({
type: LabelType.Name,
displayText: null,
text: name,
status,
});
}
}
export class Pronouns extends Label {
constructor({ display_text, pronouns, status }: API.Pronoun) {
super({
type: LabelType.Pronouns,
displayText: display_text ?? null,
text: pronouns,
status,
});
}
get pronouns(): string[] { return this.text.split('/'); }
set pronouns(to: string[]) { this.text = to.join('/'); }
shortDisplay(): string {
return this.displayText ?? this.pronouns.splice(0, 2).join('/');
}
}
export class Field {
name: string;
labels: Label[];
constructor({ name, favourite, okay, jokingly, friends_only, avoid }: API.Field) {
this.name = name;
function transpose(arr: API.Arr<string>, status: LabelStatus): Label[] {
return (arr ?? []).map(text => new Label({
displayText: null,
text,
status,
}));
}
this.labels = [
...transpose(favourite, LabelStatus.Favourite),
...transpose(okay, LabelStatus.Okay),
...transpose(jokingly, LabelStatus.Jokingly),
...transpose(friends_only, LabelStatus.FriendsOnly),
...transpose(avoid, LabelStatus.Avoid),
];
}
}

View file

@ -1,32 +0,0 @@
import type { APIError } from "./types";
const apiBase = process.env.API_BASE ?? "/api";
export default async function fetchAPI<T>(
path: string,
method = "GET",
body: any = null
) {
let headers = {};
const token =
typeof localStorage !== "undefined" &&
localStorage.getItem("pronouns-token");
if (token) {
headers = {
Authorization: token,
};
}
const resp = await fetch(`${apiBase}/v1${path}`, {
method,
headers: {
...headers,
"Content-Type": "application/json",
},
body: body ? JSON.stringify(body) : null,
});
const data = await resp.json();
if (resp.status < 200 || resp.status >= 300) throw data as APIError;
return data as T;
}

View file

@ -1,5 +1,5 @@
import { atom } from "recoil"; import { atom } from "recoil";
import { MeUser } from "./types"; import { MeUser } from "./api-fetch";
export const userState = atom<MeUser | null>({ export const userState = atom<MeUser | null>({
key: "userState", key: "userState",

View file

@ -2,9 +2,6 @@ import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { useRecoilState } from "recoil"; import { useRecoilState } from "recoil";
import Loading from "../../components/Loading"; import Loading from "../../components/Loading";
import fetchAPI from "../../lib/fetch";
import { userState } from "../../lib/state";
import { MeUser, Field } from "../../lib/types";
import cloneDeep from "lodash/cloneDeep"; import cloneDeep from "lodash/cloneDeep";
import { ReactSortable } from "react-sortablejs"; import { ReactSortable } from "react-sortablejs";
@ -21,6 +18,8 @@ import toast from "../../lib/toast";
import ReactCodeMirror from "@uiw/react-codemirror"; import ReactCodeMirror from "@uiw/react-codemirror";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown"; import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import ReactMarkdown from "react-markdown"; import ReactMarkdown from "react-markdown";
import { userState } from "../../lib/state";
import { fetchAPI, Field, MeUser } from "../../lib/api-fetch";
export default function Index() { export default function Index() {
const [user, setUser] = useRecoilState(userState); const [user, setUser] = useRecoilState(userState);

View file

@ -1,15 +1,14 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useRecoilState } from "recoil"; import { useRecoilState } from "recoil";
import fetchAPI from "../../lib/fetch";
import { userState } from "../../lib/state"; import { userState } from "../../lib/state";
import { APIError, MeUser, SignupResponse } from "../../lib/types";
import TextInput from "../../components/TextInput"; import TextInput from "../../components/TextInput";
import Loading from "../../components/Loading"; import Loading from "../../components/Loading";
import Button, { ButtonStyle } from "../../components/Button"; import Button, { ButtonStyle } from "../../components/Button";
import Notice from "../../components/Notice"; import Notice from "../../components/Notice";
import BlueLink from "../../components/BlueLink"; import BlueLink from "../../components/BlueLink";
import toast from "../../lib/toast"; import toast from "../../lib/toast";
import { fetchAPI, MeUser, SignupResponse } from "../../lib/api-fetch";
interface CallbackResponse { interface CallbackResponse {
has_account: boolean; has_account: boolean;

View file

@ -2,7 +2,7 @@ import { GetServerSideProps } from "next";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useRecoilValue } from "recoil"; import { useRecoilValue } from "recoil";
import Head from "next/head"; import Head from "next/head";
import fetchAPI from "../../lib/fetch"; import { fetchAPI } from "../../lib/api-fetch";
import { userState } from "../../lib/state"; import { userState } from "../../lib/state";
interface URLsResponse { interface URLsResponse {

View file

@ -1,26 +1,30 @@
import { GetServerSideProps } from "next"; import { GetServerSideProps } from "next";
import fetchAPI from "../../../lib/fetch";
import { Member } from "../../../lib/types";
import PersonPage from "../../../components/PersonPage"; import PersonPage from "../../../components/PersonPage";
import { Member } from "../../../lib/api";
import * as API from "../../../lib/api-fetch";
interface Props { interface Props {
member: Member; member: API.Member;
} }
export default function MemberPage({ member }: Props) { export default function MemberPage({ member }: Props) {
return <PersonPage person={member} />; return <PersonPage person={new Member(member)} />;
} }
export const getServerSideProps: GetServerSideProps = async (context) => { export const getServerSideProps: GetServerSideProps = async (context) => {
try { const userName = context.params!.user;
const member = await fetchAPI<Member>( if (typeof userName !== "string") return { notFound: true };
`/users/${context.params!.user}/members/${context.params!.member}` const memberName = context.params!.member;
); if (typeof memberName !== "string") return { notFound: true };
return { props: { member } }; try {
return {
props: {
member: await API.fetchAPI<API.Member>(`/users/${context.params!.user}/members/${context.params!.member}`),
},
};
} catch (e) { } catch (e) {
console.log(e); console.log(e);
return { notFound: true }; return { notFound: true };
} }
}; };

View file

@ -1,22 +1,21 @@
import { GetServerSideProps } from "next"; import { GetServerSideProps } from "next";
import PersonPage from "../../../components/PersonPage"; import PersonPage from "../../../components/PersonPage";
import fetchAPI from "../../../lib/fetch"; import { User } from "../../../lib/api";
import { PartialMember, User } from "../../../lib/types"; import * as API from "../../../lib/api-fetch";
interface Props { interface Props {
user: User; user: API.User;
partialMembers: PartialMember[];
} }
export default function Index({ user }: Props) { export default function Index({ user }: Props) {
return <PersonPage person={user} />; return <PersonPage person={new User(user)} />;
} }
export const getServerSideProps: GetServerSideProps = async (context) => { export const getServerSideProps: GetServerSideProps = async (context) => {
const name = context.params!.user; const userName = context.params!.user;
if (typeof userName !== "string") return { notFound: true };
try { try {
const user = await fetchAPI<User>(`/users/${name}`); return { props: { user: await API.fetchAPI<User>(`/users/${userName}`) } };
return { props: { user } };
} catch (e) { } catch (e) {
console.log(e); console.log(e);
return { notFound: true }; return { notFound: true };